istream::getline
方法返回什么?
我之所以问是因为我已经看到要遍历文件,应该这样做:
while ( file.getline( char*, int ) )
{
// handle input
}
什么被退回?
它返回一个流,以便我们可以链接操作。
但是,当您在布尔上下文中使用对象时,编译器会查找可以将其转换为可在布尔上下文中使用的类型的转换运算符。
在这种情况下,流具有explicit operator bool() const
. 当被调用时,它会检查错误标志。如果设置了failbit或badbit,则返回false,否则返回true。
在这种情况下,流具有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.
}
它返回流本身。流可以转换(通过void*
)以bool
指示其状态。在此示例中,您的while
循环将在流转换为bool
“假”时终止,这发生在您的流进入错误状态时。在您的代码中,当尝试读取文件末尾时最有可能发生这种情况。简而言之,它将读取尽可能多的内容,然后停止。
该函数返回对流对象本身的引用,该引用可用于链接进一步的读取操作:
myStream.getline(...).getline(...);
或者,因为流可以在循环或条件中隐式转换为void *
s:
while (myStream.getline(...)) {
...
}
您可以在 cplusplus.com 网站上阅读更多相关信息:
每个人都告诉你它是什么,现在让我告诉你,使用自由形式版本
std::string line;
while(getline(file, line)) // assuming file is an instance of istream
{
//
}
为什么是这个版本?它应该立即变得明显 - 你传入一个std::string
而不是一些固定大小的字符缓冲区!