在C ++中没有`while(!my_ifstream.eof()){getline(my_ifstream,line)}` [英] No `while (!my_ifstream.eof()) { getline(my_ifstream, line) }` in C++?
问题描述
在此网站上,有人写:
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
这是错误的,请仔细阅读文档为eof()
成员函数。正确的代码是:
This is wrong, read carefully the documentation for the eof() memberfunction. The correct code is this:
while( getline( myfile, line))
cout << line << endl;
为什么?
推荐答案
有两个主要原因。 @Etienne指出:除非达到文件结尾,否则读取可能失败,在这种情况下,您的第一个版本将进入无限循环。
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.
这篇关于在C ++中没有`while(!my_ifstream.eof()){getline(my_ifstream,line)}`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!