Reputation: 100648
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?
Upvotes: 25
Views: 23568
Reputation: 20039
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()
.
Upvotes: 27
Reputation: 32926
Charles did give the correct answer.
What is called is indeed std::basic_ios::operator void*()
, and not sentry::operator bool()
, which is consistant with the fact that std::getline()
returns a std::basic_istream
(thus, a std::basic_ios
), and not a sentry.
For the non believers, see:
Otherwise, as other have already said, prefer the second form which is canonical. Use not fail()
if really you want a verbose code -- I never remember whether xxx.good()
can be used instead of !xxx.fail()
Upvotes: 5
Reputation: 59827
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.
Upvotes: 8
Reputation: 119144
I would stick with the first form. While the second form may work, it is hardly explicit. Your original code clearly describes what is being done and how it is expected to behave.
Upvotes: -3