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