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

杀马特。学长 韩版系。学妹 提交于 2019-12-10 15:39:02

问题


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 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.




回答2:


A stream operation (such as reading) can fail for multiple reasons. eof() tests just one of them. To test them all, simply use the stream's void *conversion operator. That's what's done in the second snippet.



来源:https://stackoverflow.com/questions/7623999/no-while-my-ifstream-eof-getlinemy-ifstream-line-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!