C++ Simple file reading

Asked
Viewd239

1

I have a file,named f1.txt, whose contents are 75 15 85 35 60 50 45 70

Here is my code to read each integer and print them.

#include <iostream>
#include <fstream>

using namespace std;
int main(int argc, char *argv[])
{
  fstream file("f1.txt", ios::in);
  int i;
  while(!file.eof()) {
    file >> i;
    cout << i << " ";
 }

return 0;
}

But when I compiled and run the program, the output is 75 15 85 35 60 50 45 70 70. Why it is reading the last integer twice ? Any clues ?

239
  • This question has been asked one way or another many times on SO.

    Evan Teran19 октября 2009, 04:32

2 ответов

6

Try:

while(file >> i)
    cout << i << " ";
4

std::stream doesn't set eof() until a read fails, so one fix is:

while (file >> i, !file.eof()) cout << i << " ";
  • Sure: it’s a little more unclear, but I don’t mind either way.

    Simon Buchan19 октября 2009, 05:19
  • the , !file.eof() is unnecessary since file >> i will return a reference to file which when converting to a bool will yield the current stream fail state.

    Evan Teran19 октября 2009, 04:30