-1

I have to read from a file where are only few numbers. Read it, sum them up and that's it. (Learning C++). If I was using fstream::eof() function it read the last number twice, so I did it like this:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    fstream file;
    int a = 0, sum = 0;

    file.open("nums.txt",fstream::in);

    if (!file.is_open()) {
        cout << "Unable to open file!\n" << endl;
    }

    while (file >> a) {
        cout << a << endl;
        sum += a;
    }

    cout << "Sum: " << sum << endl;

    file.close();

    getchar();
    return 0;
}

Now it doesn't read last number twice, but I don't understand what is happening in while() brackets, I thought if I read 0 it would stop, but it reads it as well. Is file >> a actually returning something like "managed to read" = 1 and "fail" = 0 ??

Thanks

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
ligazetom
  • 83
  • 1
  • 8
  • 1
    Possible duplicate of [How is "std::cin>>value" evaluated in a while loop?](https://stackoverflow.com/questions/34395801/how-is-stdcinvalue-evaluated-in-a-while-loop) – Tadeusz Kopec for Ukraine Oct 03 '17 at 07:49

2 Answers2

7

Is file >> a actually returning something

Yes. It returns a reference to file itself. And std::fstream is contextually convertible to bool via its operator bool

It essentially returns the logical inverse of the streams fail() member.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
3

The >> operator, when applied to a stream, returns that same stream. This is why you can write stuff like file >> a >> b. It also happens that the stream has an operator bool() that is equivalent to !fail(). Thus, once the stream has reached eof, the operator bool() will return false, and since >> returns the stream, while (file >> a) will loop until the stream hits eof (or has an error).

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347