Monday, August 27, 2018

C++ - why cin.eof() read last char twice?

End of file is detected by failing an input operation.




So, in



    cin>>x;
cout<<"char: "<< x << endl;


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.



#include
using namespace std;
int main()
{
char x;
while( cin >> x )

{
cout<<"char: "<< x << endl;
}
}


Here the expression cin >> x performs an input operation that might update x, and as its expression result returns a reference to the stream, i.e. to cin. So cin is 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 expression cin >> x as condition is equivalent to writing !(cin >> x).fail() or, as a comma expression, (cin >> x, !cin.fail())).

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...