std::basic_ios::operator bool

operator void*() const;
(1) (until C++11)
explicit operator bool() const;
(2) (since C++11)

Checks whether the stream has no errors.

1) Returns a null pointer if fail() returns true, otherwise returns a non-null pointer. This pointer is implicitly convertible to bool and may be used in boolean contexts.
2) Returns true if the stream has no errors and is ready for I/O operations. Specifically, returns !fail().

This operator makes it possible to use streams and functions that return references to streams as loop conditions, resulting in the idiomatic C++ input loops such as while(stream >> value) {...} or while(getline(stream, string)){...}. Such loops execute the loop's body only if the input operation succeeded.

Parameters

(none).

Return value

true if the stream has no errors, false otherwise.

Example

#include <iostream>
#include <sstream>
 
int main()
{
    std::istringstream s("1 2 3 error");
    int n;
    std::cout << std::boolalpha << "(bool)s is " << (bool)s << '\n';
    while (s >> n) {
        std::cout << n << '\n';
    }
    std::cout << std::boolalpha << "(bool)s is " << (bool)s << '\n';
}

Output:

(bool)s is true
1
2
3
(bool)s is false

See also

The following table shows the value of basic_ios accessors (good(), fail(), etc.) for all possible combinations of ios_base::iostate flags:

ios_base::iostate flags basic_ios accessors
eofbit failbit badbit good() fail() bad() eof() operator bool operator!
false false false true false false false true false
false false true false true true false false true
false true false false true false false false true
false true true false true true false false true
true false false false false false true true false
true false true false true true true false true
true true false false true false true false true
true true true false true true true false true
doc_CPP
2016-10-11 10:00:49
Comments
Leave a Comment

Please login to continue.