I have a loop that reads each line in a file using getline()
:
istream is; string line; while (!getline(is, line).eof()) { // ... }
I noticed that calling getline()
like this also seems to work:
while (getline(is, line))
What's going on here? getline()
returns a stream reference. Is it being converted to a pointer somehow? Is this actually a good practice or should I stick to the first form?
When getline is successful, it returns the number of characters read (including the newline, but not including the terminating null). This value enables you to distinguish null characters that are part of the line from the null character inserted as a terminator.
Returned value If successful, getline() returns the number of characters that are read, including the newline character, but not including the terminating null byte ( '\0' ). This value can be used to handle embedded null bytes in the line read.
getline(cin, newString); begins immediately reading and collecting characters into newString and continues until a newline character is encountered. The newline character is read but not stored in newString.
The C++ getline() is an in-built function defined in the <string. h> header file that allows accepting and reading single and multiple line strings from the input stream. In C++, the cin object also allows input from the user, but not multi-word or multi-line input. That's where the getline() function comes in handy.
The istream
returned by getline()
is having its operator void*()
method implicitly called, which returns whether the stream has run into an error. As such it's making more checks than a call to eof()
.
Updated:
I had mistakenly pointed to the basic_istream documentation for the operator bool() method on the basic_istream::sentry class, but as has been pointed out this is not actually what's happening. I've voted up Charles and Luc's correct answers. It's actually operator void*() that's getting called. More on this in the C++ FAQ.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With