std::basic_ios<CharT,Traits>::operator bool

From cppreference.com
< cpp‎ | io‎ | basic ios
 
 
Input/output library
I/O manipulators
C-style I/O
Buffers
(deprecated in C++98)
Streams
Abstractions
File I/O
String I/O
Array I/O
(deprecated in C++98)
(deprecated in C++98)
(deprecated in C++98)
Synchronized Output
Types
Error category interface
(C++11)
 
 
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 << "s is " << static_cast<bool>(s) << '\n';
    while (s >> n) {
        std::cout << n << '\n';
    }
    std::cout << "s is " << static_cast<bool>(s) << '\n';
}

Output:

s is true
1
2
3
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