Good day! I have a static listOfStudents() method that opens a text file and reads my data from there ...

My text file looks like this:

Text file

As you can see in the picture a simple text file with data.

My task is to take from there the Name and Surname and display:

Fully my method looks like this:

 static void listStudents(){ cout << endl << "List students" << endl<< endl; ifstream textfile; string line; string unused = ""; textfile.open("students.txt"); if(textfile.is_open()){ int count = 0; for(int i = 0 , j = 0; !textfile.eof(); i++){ if(i == j){ count++; textfile >> line; cout << count << ": " << line; textfile >> line; cout << " " << line << endl; j+=11; }else{ textfile >> unused; unused = ""; } } }else{ cout << "You don't have any students!" << endl; } textfile.close(); cout << endl << endl; main(); } 

I have 4 students in a text file, and when I display the following happens:

Problem

As you can see, everything shows up normally, but at the end, for some reason, it generates another 1 line where the name of the previous student is doubled.


Question: Why does he do that? And how can I fix this?

  • The classic mistake. A cycle with a precondition !eof is almost always an error in C and C ++. - AnT

1 answer 1

As you can see, everything shows up normally, but at the end, for some reason, it generates another 1 line where the name of the previous student is doubled.

Because you do not need to check

 !textfile.eof() 

At the time of verification, the end of the file has not yet been reached - it is achieved only when trying to read. Accordingly, nothing can be read and the previous value is stored in the variable. And the next check is performed only before the next iteration of the loop.

  • And how should I write? - E1mir
  • @KryTer_NexT, something like this: for (...; textfile >> line; ...) . - Qwertiy
  • then it turns out that I have to rebuild the whole cycle under a condition so to speak? - E1mir
  • @KryTer_NexT, you can still if (!(textfile >> line)) break; . But in general, with the condition it would be usually more logical. - Qwertiy
  • All) Understood the error) Thanks for the tips :) - E1mir