文件输入无法按预期工作

时间:2012-10-06 04:25:02

标签: c++ ifstream

在main中:

ifstream file("text.txt");
string line;
while (file) {
    file>>line;
    cout<<line<<endl;
}
text.txt中的

hello
goodbye

输出:

hello
goodbye
goodbye

为什么最后一行打印两次?

1 个答案:

答案 0 :(得分:2)

复制:当你第一次读''再见'时,你不知道你到达了文件的末尾并进入下一次迭代。然后无法读取,设置eof位,但打印出line的当前值,这仍然是'再见'。