I'm a std::getline(...)
virgin and having consulted documentation and example at cppreference.com, 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, ...)
is input
, i.e. a reference to the first argument.
How, then, can the return value of getline
be used as the while loop's condition, which needs to be of type bool
?
Does std::ifstream
implement an operator bool()
?
Does std::ifstream implement an operator bool()?
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) {...}
orwhile(getline(stream, string)){...}