C++ std::getline() 返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/259269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:06:54  来源:igfitidea点击:

std::getline() returns

c++getline

提问by Ferruccio

I have a loop that reads each line in a file using getline():

我有一个循环,它使用以下命令读取文件中的每一行getline()

istream is;
string line;
while (!getline(is, line).eof())
{
    // ...
}

I noticed that calling getline()like this also seems to work:

我注意到这样的调用getline()似乎也有效:

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?

这里发生了什么?getline()返回一个流引用。它是否以某种方式转换为指针?这实际上是一个好习惯还是我应该坚持第一种形式?

回答by Charles Anderson

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

istream通过返回getline()由具有其操作void*()方法隐含地调用,它返回是否该流已碰上一个错误。因此,它比调用eof().

回答by Todd Gamblin

Updated:

更新:

I had mistakenly pointed to the basic_istream documentationfor 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.

我错误地指向basic_istream::sentry 类上的 operator bool() 方法的basic_istream 文档,但正如已经指出的那样,这实际上并不是正在发生的事情。我已经投票支持查尔斯和卢克的正确答案。它实际上是被调用的 operator void*() 。在 C++ FAQ 中有更多关于这个的信息

回答by Luc Hermitte

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.

所谓的确实是std::basic_ios::operator void*(),而不是sentry::operator bool(),这与std::getline()返回 a std::basic_istream(因此, a std::basic_ios)而不是哨兵的事实一致。

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

否则,正如其他人已经说过的,更喜欢规范的第二种形式。fail()如果你真的想要一个冗长的代码,请不要使用——我不记得是否xxx.good()可以使用代替!xxx.fail()

回答by e.James

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.

我会坚持第一种形式。虽然第二种形式可能有效,但它几乎不明确。您的原始代码清楚地描述了正在执行的操作以及预期的行为方式。