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? 回答1: 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