1

I've seen many loops like this to read streams:

while(std::getline(iss, temp, ' ')) {
    ...
}

But I never understood why it worked. In the documentation for std::getline, it says that it returns the stream, and I don't understand how that is translated into a bool value. Is it reading the eof flag or something? If so, wouldn't this be more accurate:

while(!iss.eof()) {
    std::getline(iss, temp, ' ');
}

BrianZhang
  • 153
  • 1
  • 8
  • Handy reading: [Why istream object can be used as a bool expression?](https://stackoverflow.com/questions/8117566/why-istream-object-can-be-used-as-a-bool-expression) – user4581301 Jun 25 '21 at 16:06
  • EOF is one condition it checks for, but it also makes sure the read succeeded. Your EOF loop would be an infinite loop if a read fails, e.g., the physical drive hardware fails or becomes disconnected. – chris Jun 25 '21 at 16:06

2 Answers2

4

while statements don't require a bool specifically for their condition expression. They require a type that is convertible to bool.

std::getline returns a type derived from std::basic_ios, which is convertible to bool.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
4

std::getline inherits std::basic_istream, that inherits std::basic_ios, that implements std::basic_ios<CharT,Traits>::operator bool.

while requires a bool resulting expression, thus

while(std::getline(iss, temp, ' ')) {
    ...
}

is attempted by the compiler under the hood like as

while(static_cast<bool>(std::getline(iss, temp, ' '))) {
    ...
}

and conversion is performed successfully as

while(std::getline(iss, temp, ' ').operator bool()) {
    ...
}
273K
  • 29,503
  • 10
  • 41
  • 64