我刚刚开始使用 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;
}
最佳答案
getline
在 Tfile
到达文件末尾时设置 eofbit
。这会导致 Tfile
的 operator 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/