Question

I have a flimsy understanding of how/why istream can be used in conditionals. I have read this question:(Why istream object can be used as a bool expression?).

I don't understand why this compiles without error…

while (cin >> n) {
    // things and stuff
}

…while this fails to compile (message error: invalid operands to binary expression ('int' and '__istream_type' (aka 'basic_istream<char, std::char_traits<char> >')))

while (true == (cin >> n)) {
    // things and stuff
}
Was it helpful?

Solution

Because the implicit conversion operator of cin is

operator void*() const { ... }

and it can evaluate to zero, so you can check it against zero

while (cin >> x) {}

Conversion operator for bool declared as explicit so your expression will not invoke it:

explicit operator bool(){ ... }

So, you need an explicit cast:

if (true == static_cast<bool>(cin >> a))
{
}

OTHER TIPS

cin >> n returns an istream&. Because the result is used in a comparison, the compiler searches for an operator==(bool, istream), which it cannot find. Therefore, you get an error message.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top