c++ - std::getline() 如何等同于 bool?

标签 c++ stl operator-keyword getline conversion-operator

<分区>

我是 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, ...) 的返回值是input ,即对第一个参数的引用。

那么getline的返回值如何用作 while 循环的条件,需要是 bool 类型?

是否 std::ifstream实现 operator bool()

最佳答案

Does std::ifstream implement an operator bool()?

It does:

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)){...}

关于c++ - std::getline() 如何等同于 bool?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40298927/

相关文章:

c - C中的按位逻辑

c++ - 与运算符重载不匹配运算符+错误

c++ - 无法将参数 1 从 int 转换为 int && 错误

c++ - 一组元组 (i, v) 使得所有元组具有不同的 i 值

c++ - 是否可以在类似 STL 的容器中使用 WinRT 对象?

c++ - 使用比较功能

C++ 将自定义类型的转换运算符重载为 std::string

c++ - ShowWindow仅在最后一次最小化时才还原窗口

c++ - 使用 boost program-options 的无效选项值异常

c++ - 我如何表示十六进制数?