Monday 27 August 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...