Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No `while (!my_ifstream.eof()) { getline(my_ifstream, line) }` in C++?

On this website, someone writes:

while (! myfile.eof() )
{
   getline (myfile,line);
   cout << line << endl;
}

This is wrong, read carefully the documentation for the eof() memberfunction. The correct code is this:

while( getline( myfile, line))
    cout << line << endl;

Why is this?

like image 672
Felix Dombek Avatar asked Dec 22 '22 08:12

Felix Dombek


1 Answers

There are two primary reasons. @Etienne has pointed out one: reading could fail for some reason other than reaching the end of the file, in which case your first version will go into an infinite loop.

Even with no other failures, however, the first won't work correctly. eof() won't be set until after an attempt at reading has failed because the end of the file was reached. That means the first loop will execute one extra iteration that you don't really want. In this case, that'll just end up adding an extra blank (empty) line at the end of the file. Depending on what you're working with, that may or may not matter. Depending on what you're using to read the data, it's also fairly common to see the last line repeated in the output.

like image 91
Jerry Coffin Avatar answered Dec 31 '22 13:12

Jerry Coffin