Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can std::cin return a bool and itself at the same time?

Tags:

c++

cin

I'm reading a book on C++ that says that if I use the >> operator it returns the object at the left side of the operator so in this example

std::cin >> value1; 

the code returns std::cin.

But if I do this

while(std::cin >> value1) 

My code will be in the loop until there is a std::cin error so that must mean that the operator returns a bool that is true when std::cin does not fail and false when std::cin fails.

Which is one is it?

like image 640
gigi Avatar asked Aug 16 '16 14:08

gigi


People also ask

Can you cin a bool in C++?

No, you cannot cin a boolean, although you wont get an error when you try to, the program will wont pause for you to enter the value of the boolean variable.

Does CIN return true?

Returns true if the stream has no errors and is ready for I/O operations.

Does CIN overwrite?

Every time you read from cin to a variable, the old contents of that variable is overwritten.


1 Answers

[...] so that must mean that the operator returns a bool [...]

Nope, it returns std::cin (by reference). The reason why while(std::cin >> value); works is because std::istream (which is the type of std::cin) has a conversion operator.

A conversion operator basically permits a class to be implicitly (if it is not marked explicit) to be converted to a given type. In this case, std::istream defines its operator bool to return whether an error (typically failbit) occurred;

[std::ios_base::operator bool()]

Returns true if the stream has no errors and is ready for I/O operations. Specifically, returns !fail().


explicit operator bool() const; 

Note than even though the operator is explicit (which shouldn't allow implicit conversions like if (std::cin);), the qualifier is ignored when used in a context that requires a bool, like if, while loops and for loops. Those are exceptions though, not rules.

Here is an example:

if (std::cin >> value);  //OK, a 'std::istream' can be converted into a 'bool', which                           //therefore happens implicitly, without the need to cast it:   if (static_cast<bool>(std::cin >> value)); //Unnecessary  bool b = std::cin >> value;  //Error!! 'operator bool' is marked explicit (see above), so                               //we have to call it explicitly:  bool b = static_cast<bool>(std::cin >> value); //OK, 'operator bool' is called explicitly 
like image 87
Rakete1111 Avatar answered Sep 20 '22 19:09

Rakete1111