I'm writing a program which takes several variables from a text file.
When the program finds EOF,
it ends entering data.
int main()
{
int val, count = 0;
ifstream fileIn;
fileIn.open("num.txt");
fileIn >> val;
while (fileIn)
{
++count;
cout << "number: " << val << endl;
fileIn >> val;
}
cout << "count: " << count << endl;
fileIn.close();
return 0;
}
num.txt
file: 11 22 33 44
Program output:
number: 11
number: 22
number: 33
number: 44
count: 4
Everything is OK. But if I change the while condition section from fileIn
to fileIn.good()
,
the program output will look like this:
number: 11
number: 22
number: 33
count: 3
It skips last value now.
Why is this happening and what's the difference between fileIn
and fileIn.good()
?