20

istream::getline方法返回什么?

我之所以问是因为我已经看到要遍历文件,应该这样做:

while ( file.getline( char*, int ) )
{
    // handle input
}

什么被退回?

4

5 回答 5

22

它返回一个流,以便我们可以链接操作。

但是,当您在布尔上下文中使用对象时,编译器会查找可以将其转换为可在布尔上下文中使用的类型的转换运算符。

C++11

在这种情况下,流具有explicit operator bool() const. 当被调用时,它会检查错误标志。如果设置了failbit或badbit,则返回false,否则返回true。

C++03

在这种情况下,流具有operator void*() const. 由于这会产生一个指针,因此它可以在布尔上下文中使用。当被调用时,它会检查错误标志。如果设置了failbit或badbit,那么它返回NULL,这相当于FALSE,否则它返回一个指向self的指针(或其他有效的东西,尽管你不应该使用这个事实))。

用法

因此,您可以在需要布尔测试的任何上下文中使用流:

if (stream >> x)
{    
}

while(stream)
{
    /* do Stuff */
}

Note: It is bad idea to test the stream on the outside and then read/write to it inside the body of the conditional/loop statement. This is because the act of reading may make the stream bad. It is usually better to do the read as part of the test.

while(std::getline(steam, line))
{
    // The read worked and line is valid.
}
于 2011-01-16T22:17:47.390 回答
5

参考看。返回的 istream通过隐式转换getline转换为 bool以检查操作是否成功。这种转换使 of 的使用成为.if(mystream.getline(a,b))if(!mystream.getline(a,b).fail())

于 2011-01-16T21:58:02.260 回答
3

它返回流本身。流可以转换(通过void*)以bool指示其状态。在此示例中,您的while循环将在流转换为bool“假”时终止,这发生在您的流进入错误状态时。在您的代码中,当尝试读取文件末尾时最有可能发生这种情况。简而言之,它将读取尽可能多的内容,然后停止。

于 2011-01-16T21:59:46.423 回答
2

该函数返回对流对象本身的引用,该引用可用于链接进一步的读取操作:

myStream.getline(...).getline(...);

或者,因为流可以在循环或条件中隐式转换为void *s:

while (myStream.getline(...)) {
    ...
}

您可以在 cplusplus.com 网站上阅读更多相关信息:

http://cplusplus.com/reference/iostream/istream/getline/

于 2011-01-16T21:58:09.110 回答
0

每个人都告诉你它是什么,现在让我告诉你,使用自由形式版本

std::string line; 
while(getline(file, line)) // assuming file is an instance of istream
{
//
}

为什么是这个版本?它应该立即变得明显 - 你传入一个std::string而不是一些固定大小的字符缓冲区!

于 2011-01-16T22:17:00.657 回答