StoneThrow StoneThrow - 1 year ago 137
C++ Question

How is std::getline() equated with bool?

I'm a

virgin and having consulted documentation and example at, I'm confused by example code such as this:

#include <sstream>
#include <string>

int main(int argc, char* argv[])
std::string line;
std::ifstream infile("sample.txt");

while (std::getline(infile, line))
// Do stuff

return 0;

...specifically the while statement:
while (std::getline(infile, line))

The noted documentation says the return value of
std::getline(std::basic_istream<CharT,Traits>& input, ...)
, i.e. a reference to the first argument.

How, then, can the return value of
be used as the while loop's condition, which needs to be of type

implement an
operator bool()

Answer Source

Does std::ifstream implement an operator bool()?

It does:

Checks whether the stream has no errors. <...> 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)){...}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download