I am writing a program that takes several variables from a text file. When the program finds EOF,
it finishes 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 fine. But if I change the while status section from fileInto fileIn.good(), the
output of the program will look like this:
number: 11
number: 22
number: 33
count: 3
Now it skips the last value. Why is this happening and what is the difference between fileIn
and fileIn.good()?
source
share