std::getline() 如何等同于 bool?
How is std::getline() equated with bool?
我是 std::getline(...)
处女,在 cppreference.com 上查阅了文档和示例,我对这样的示例代码感到困惑:
#include <sstream>
#include <string>
int main(int argc, char* argv[])
{
std::string line;
std::ifstream infile("sample.txt");
while (std::getline(infile, line))
{
// Do stuff
}
return 0;
}
...特别是 while 语句:while (std::getline(infile, line))
.
提到的文档说 std::getline(std::basic_istream<CharT,Traits>& input, ...)
的 return 值是 input
,即对第一个参数的引用。
那么,getline
的return值如何作为while循环的条件,需要类型为bool
?
std::ifstream
是否实现了 operator bool()
?
Does std::ifstream implement an operator bool()?
Checks whether the stream has no errors. <...> Returns true if the stream has no errors and is ready for
I/O operations. Specifically, returns !fail()
.
This operator makes it possible to use streams and functions that
return references to streams as loop conditions, resulting in the
idiomatic C++ input loops such as while(stream >> value) {...}
or
while(getline(stream, string)){...}
我是 std::getline(...)
处女,在 cppreference.com 上查阅了文档和示例,我对这样的示例代码感到困惑:
#include <sstream>
#include <string>
int main(int argc, char* argv[])
{
std::string line;
std::ifstream infile("sample.txt");
while (std::getline(infile, line))
{
// Do stuff
}
return 0;
}
...特别是 while 语句:while (std::getline(infile, line))
.
提到的文档说 std::getline(std::basic_istream<CharT,Traits>& input, ...)
的 return 值是 input
,即对第一个参数的引用。
那么,getline
的return值如何作为while循环的条件,需要类型为bool
?
std::ifstream
是否实现了 operator bool()
?
Does std::ifstream implement an operator bool()?
Checks whether the stream has no errors. <...> Returns true if the stream has no errors and is ready for I/O operations. Specifically, returns
!fail()
.This operator makes it possible to use streams and functions that return references to streams as loop conditions, resulting in the idiomatic C++ input loops such as
while(stream >> value) {...}
orwhile(getline(stream, string)){...}