以下的C++代码使用一个ifstream对象从文本文件中读取整数(每行一个)直到遇到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:
->input.txt:
10
20
30
输出:
10
20
30
30
注意:为了使代码更加简洁,我省略了所有的错误检查代码。以上行为在Windows(Visual C ++),cygwin(gcc)和Linux(gcc)上均可见。
while(true)
,似乎更好的写法是while(file.good())
。 - PHF