以下C++代码使用ifstream的对象读取从文本文件中的整数(其具有每行一个数),直到它碰到EOF。为什么它读取最后一行的整数两次?如何解决这个问题?从文本文件中读取直到EOF重复最后一行
代码:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream iFile("input.txt"); // input.txt has integers, one per line
while (!iFile.eof())
{
int x;
iFile >> x;
cerr << x << endl;
}
return 0;
}
input.txt中:
10
20
30
输出:
10
20
30
30
注意:我跳过了所有的错误检查代码,以保持代码片段小。上述行为可以在Windows(Visual C++),cygwin(gcc)和Linux(gcc)上看到。
使用'while(iFile >> x)'。这读取整数并返回流。当流被用作bool值时,它会检查流是否有效。有效意味着eof()和bad()都是错误的。请参阅http://stackoverflow.com/questions/21647/c-reading-from-text-file-until-eof-repeats-last-line#21666 – 2008-09-23 07:48:02
与注释相同的精神:而不是`while(true)`,看起来最好写'while(file.good())` – PHF 2012-04-13 15:14:42