提问人:Jason Jia 提问时间:2/19/2022 最后编辑:user12002570Jason Jia 更新时间:7/11/2022 访问量:80
在 c++ 中读取文件时打印两次最后一个值 [duplicate]
Getting last value printed twice when reading file in c++ [duplicate]
问:
我是 c++ 的新手。目前,我正在学习如何读取和写入文件。我创建了一个文件“nb.txt”,内容如下:
1 2 3 4 5 6 7
2 3 4 5 6 7 9
我正在使用一个简单的程序来读取此文件,循环直到达到EOF。
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream in("nb.txt");
while (in) {
int current;
in >> current;
cout << current << " ";
}
}
我所期望的是程序将输出所有值。 但我真正得到的是:
1 2 3 4 5 6 7 2 3 4 5 6 7 9 9
输出中有一个多个“9”。我不明白发生了什么!是因为while循环吗?
谁能帮我弄清楚为什么还有另一个“9”?谢谢!
答:
2赞
user12002570
2/19/2022
#1
问题是读取后,最后一个值(在本例中)尚未设置为文件末尾。因此,程序再次进入循环,然后读取(现在将其设置为文件末尾),并且不对变量进行任何更改,并且以当前值(即 )打印变量。9
in
while
in
current
9
要解决此问题,您可以执行以下操作:
int main() {
ifstream in("nb.txt");
int current=0;
while (in >> current) { //note the in >> curent
cout << current << " ";
}
}
上面程序的输出可以在这里看到:
1 2 3 4 5 6 7 2 3 4 5 6 7 9
评论
iostream::eof(
) 在循环条件中(即while (!stream.eof()))
被认为是错误的?