The first problem is you read a number into x and print it out, but don't add it to the sum. The second problem is using fin.fail() as the loop condition, it's basically the same as using feof() , which is wrong.
Try this instead:
// read text from file
int ne(0);
int oe(0);
while (fin >> x) {
cout << "Read integer: " << x << endl;
sum += x;
if (x % 2 == 0)
++ne;
else
++oe;
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Why is using feof() (which is the equivalent of !fin.fail()) as the loop condition wrong?
I posted a link. Basically it's a timing issue. The error flags aren't set untilafter you try and fail to read from the stream. Unless the loop contains a further sanity check, you'll be working with data from the previous iteration. It's a "the last record is processed twice" situation.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401