我在理解C++中的文件输入流时感到很挣扎。我有一个代码片段如下:ifstream.eof()在C++中没有评估为true
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream in("x.txt");
bool done = false;
do {
string input = "";
getline(in,input);
int x1;
int x2;
in >> x1;
in >> x2;
cout << input << " " << x1 << " " << x2 << endl;
in.ignore();
if(in.eof()) {
done = true;
cout << "reached eof" << endl;
}
} while(!done);
return 0;
}
随着文件x.txt阅读如下
task1
12
1313
task2
13
1414
[blank line]
注意在输入文件的末尾故意包含空行的。所有这一切意味着输入“1414”后按下了输入/返回键。
我的预期输出是
task1 12 1313
task2 13 1414
reached eof
但实际上,输出
task1 12 1313
task2 13 1414
13 1414
reached eof
我明白,按enter内的输入文件生成一个隐换行符,并使用像一个语句之前getline(ifstream, string)
我们应该ignore()
那下一个换行符。这就是说,为什么ifstream.eof()没有评估为真,即使在'1414'之后的隐含换行符是ignore()
?
'而(在X1 >> >> X2)' – Borgleader 2014-12-03 15:31:33
你为什么不测试的返回值'getline'? 'in >> x1'和'in >> x2'同样的问题?如果您有问题,我/ O **检查I/O工作** – 2014-12-03 15:32:29
这基本上是http://stackoverflow.com/q/5605125/981959具有不同(但仍然是错误的)环 – 2014-12-03 15:34:45