Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::getline() returns

Tags:

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?

like image 210
Ferruccio Avatar asked Nov 03 '08 16:11

Ferruccio


People also ask

What does STD Getline return?

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.

What does Getline return at end-of-file C++?

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.

Does Getline return newline?

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.

What does getline () do in C++?

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.


2 Answers

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().

like image 94
Charles Anderson Avatar answered Sep 20 '22 15:09

Charles Anderson


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.

like image 37
Todd Gamblin Avatar answered Sep 20 '22 15:09

Todd Gamblin