std::getline() returns

不想你离开。 提交于 2019-11-27 11:06:33

问题


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?


回答1:


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




回答2:


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.




回答3:


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:

  • std::basic_ios::operator void*() documentation on cppreference site,
  • The The Safe Bool Idiom article on artima,
  • C++ FAQ lite §15.4,
  • the standard, ...

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




回答4:


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.



来源:https://stackoverflow.com/questions/259269/stdgetline-returns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!