【发布时间】:2010-09-06 12:06:48
【问题描述】:
以下 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:
10
20
30
输出:
10
20
30
30
注意:我已跳过所有错误检查代码以保持代码 sn-p 小。在 Windows (Visual C++)、cygwin (gcc) 和 Linux (gcc) 上可以看到上述行为。
【问题讨论】: