以下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;
}
输入.txt:
10
20
30
输出:
10
20
30
30
注意:我已跳过所有错误检查代码以保持代码片段较小。在 Windows (Visual C++)、cygwin (gcc) 和 Linux (gcc) 上可以看到上述行为。