C++ 为什么 getline() 结束 while 循环?

标签 c++ getline

我刚刚开始使用 C++ 处理文件,但我对文件对象和 getline() 的工作方式还是陌生的。

所以我有点理解 getline() 函数及其工作原理,并且当在 bool 上下文中使用时它通过 void* 返回一个 bool 值,但我不明白的是为什么在代码中 while 循环不不会导致无限循环或错误,因为没有任何语句可以终止循环,例如 break。 非常感谢您的帮助!

我唯一能特别想到的是,当 getline() 执行其操作并通过每一行工作时,它会主动更改 while(Tfile) 的状态以及到达文件末尾时 while(Tfile)不再是真的,这会导致循环终止,但我不太确定。

ifstream Tfile("player.txt");
string line;
while(Tfile){
        if (getline(Tfile, line))
    cout << line << endl;   
}

最佳答案

getlineTfile 到达文件末尾时设置 eofbit。这会导致 Tfileoperator bool 评估为 false,然后终止循环。

参见 iostate , getline's return specification , 和 ios operator bool .

请注意,由于 getline 返回对您传递给它的流的引用,因此该循环的惯用形式是:

ifstream Tfile("player.txt");
string line;
while(getline(Tfile, line)) {
  cout << line << endl;   
}

关于C++ 为什么 getline() 结束 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54317062/

相关文章:

c++ - "No match for operator="试图在 C++ 中遍历映射

c++ - constexpr operator++(int) (post-increment) 是否有任何应用

c++ - 我可以获取数组的最后一个元素的地址吗?

c++ - SSL_connect() 产生证书验证失败

c++ - 如何在不阻塞输入的情况下使用 getline?

c - Xcode 4.3中getline c函数的实现在哪里?

c++ - 线程池类 : can't pass the args straight

c - 如何将整行插入到c中的节点中?

c++ - 清除 eof 位不适用于 while 循环

c - 尽管导入了 stdio,但 getline 未在此范围内声明