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?
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.
Returns true if the stream has no errors and is ready for I/O operations.
Every time you read from cin to a variable, the old contents of that variable is overwritten.
[...] 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With