Namespaces
Variants
Views
Actions

std::basic_ios::operator bool

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

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 context.

2) Returns true if the stream has no errors occurred and is ready of 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.

Contents

[edit] Parameters

(none)

[edit] Return value

true if the stream has no errors occurred, false otherwise.

[edit] 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

[edit] See also

checks if no error has occurred i.e. I/O operations are available
(public member function) [edit]
checks if a non-recoverable error has occurred
(public member function) [edit]
checks if a recoverable error has occurred
(public member function) [edit]
checks if end-of-file has been reached
(public member function) [edit]
checks if an error has occurred (synonym of fail())
(public member function) [edit]