'!' illegal operation function expression

Hello, I am trying to identify how many even and odd numbers I have in a text file using while loop.
The code shows an error in the while loop specifically.
Here is the code, thanks.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <iostream>
#include <fstream>
using namespace std;

int main()
{
    int even = 0, odd = 0;
    int value;
    ifstream file3("evenodd.txt");

    while (!file3.eof) {
        file3 >> value;
        if (value % 2 == 0) {
            even++;
        }
        else {
            odd++;
        }
        cout << " Even count: " << even << " ";
        cout << "Odd count: " << odd << " ";
    }
}
This would fix the syntax
 
while (!file3.eof() ) 


But using eof() like that is wrong, so write instead
1
2
3
4
5
6
7
8
while ( file3 >> value ) {
        if (value % 2 == 0) {
            even++;
        }
        else {
            odd++;
        }
}

Thank you for the answer, why is using it the way you typed it wrong? It still reads the numbers for me.
It still reads the numbers for me.

How many numbers does it read? If evenodd.txt contains two numbers, like this for example:

1 2


what does your code tell you for even count and odd count?
why is using it the way you typed it wrong

Do not loop on (! stream.eof()) or (stream.good()). This does not work the way you expect. The eof bit is set true only after you make a read attempt on the file. This means after you read the last record of the file, eof is still false. Your attempt to read past the last record sets eof, but you're not checking it there. You proceed as if you had read a good record. This will result in reading an extra (bad) record. The correct way to deal with this is to put the >> (or getline) operation as the condition in the while statement.
1
2
3
  while (stream >> var) // or while (getline(stream,var))
  {  //  Good operation
  }

Topic archived. No new replies allowed.