I'm new to c . Currently I'm learning how to read and write to a file. I've created a file "nb.txt" with content like this:
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.
#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. I don't understand what's happening! Is it because of the while loop?
Can anyone help me to figure out why there is another "9"? Thanks!
CodePudding user response:
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. 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
).
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