简体   繁体   English

在 C++ 中读取文件时获取最后一个值打印两次

[英]Getting last value printed twice when reading file in c++

I'm new to c++.我是 C++ 新手。 Currently I'm learning how to read and write to a file.目前我正在学习如何读取和写入文件。 I've created a file "nb.txt" with content like this:我创建了一个文件“nb.txt”,内容如下:

1 2 3 4 5 6 7
2 3 4 5 6 7 9

I'm using a simple program to read this file, looping until reached EOF.我正在使用一个简单的程序来读取这个文件,循环直到到达 EOF。

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ifstream in("nb.txt");
    while (in) {
        int current;
        in >> current;
        cout << current << " ";
    }
}

What I'm expecting is the program will output all of the values.我期待的是程序将输出所有的值。 But what I'm really getting is this:但我真正得到的是:

1 2 3 4 5 6 7 2 3 4 5 6 7 9 9

There's a multiple "9" in the output.输出中有多个“9”。 I don't understand what's happening!我不明白发生了什么! Is it because of the while loop?是因为while循环吗?

Can anyone help me to figure out why there is another "9"?谁能帮我弄清楚为什么还有另一个“9”? Thanks!谢谢!

The problem is that after you read the last value(which is 9 in this case) in is not yet set to end of file .问题是,在您读取最后一个值(在本例中为9in尚未设置为end of file So the program enters the while loop one more time, then reads in (which now sets it to end of file ) and no changes are made to the variable current and it is printed with its current value(which is 9 ).因此程序再次进入while循环,然后读in (现在将其设置为end of file )并且对变量current没有任何更改,并以其当前值(即9 )打印。

To solve this problem, you can do the following:解决此问题,您可以执行以下操作:

int main() {
    ifstream in("nb.txt");
    int current=0;
    while (in >> current) {  //note the in >> curent
       cout << current << " ";
    }
}

The output of the above program can be seen here :上述程序的输出可以在这里看到:

1 2 3 4 5 6 7 2 3 4 5 6 7 9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM