Possible Duplicate:
Why is iostream::eof inside a loop condition considered wrong?
I’ve got very simple question…
#include<iostream>
using namespace std;
int main()
{
char x;
while(!cin.eof())
{
cin>>x;
cout<<"char: "<< x << endl;
}
return 0;
}
Why when i try to run this code on Linux:
./file_name < test_file.txt
The result is:
char: a
char: b
char: c
char: d
char: d
when test_file.txt is only:
abcd
End of file is detected by failing an input operation.
So, in
the output statement is executed even when the input operation fails.
And when it fails, it doesn’t update
x.Instead of testing
.eof(), test.fail().You can do that by using the stream object directly as a condition, e.g.
Here the expression
cin >> xperforms an input operation that might updatex, and as its expression result returns a reference to the stream, i.e. tocin. Socinis being used directly as a condition. That invokes a conversion to boolean, which is defined such that it on its own is equivalent to!cin.fail()(i.e., the expressioncin >> xas condition is equivalent to writing!(cin >> x).fail()or, as a comma expression,(cin >> x, !cin.fail())).