Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Introduction To C++ IO Streams

I got a snippet of code from this article and I'm confused as to how it works? The snippet starts by saying:

You can detect that a particular read or write operation failed by testing the result of the read. For example, to check that a valid integer is read from the user, you can do this:

int x;
if ( cin >> x ) 
{
    cout << "Please enter a valid number" << endl;
}

This works because the read operation returns a reference to the stream.

I understand that the cin >> x operation returns a reference to cin but I'm still confused as to how evaluating the reference to the standard input stream object allows you to check that the input is a valid integer.

like image 722
DanielJG Avatar asked Feb 11 '14 21:02

DanielJG


2 Answers

cin is an instance of istream template class. operator >> acts on this istream instance to load input into data and returns a reference to this istream. Then in while condition it is tested by a call to cin::operator void*() const (explicit operator bool() const in C++11) which invokes fail() function to test if operation succeeded. This is why you can use this operation in while condition

while ( cin >> x)
{
   //...
like image 61
4pie0 Avatar answered Sep 29 '22 05:09

4pie0


According to the documentation ( http://www.cplusplus.com/reference/ios/ios/operator_bool/ ), the operator

explicit operator std::ios::bool() const;

"Returns whether an error flag is set (either failbit or badbit)." and "The function returns false if at least one of these error flags is set, and true otherwise."

Thus when the if statement casts the cin stream to bool, this operator returns false if the stream has an error flag set, and true otherwise.

like image 42
aldo Avatar answered Sep 29 '22 06:09

aldo