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

C++ Why does getline() end the while loop?

我刚刚开始使用C语言处理文件,但是我仍然对文件对象和getline()的工作方式还不了解。

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

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

1
2
3
4
5
6
ifstream Tfile("player.txt");
string line;
while(Tfile){
        if (getline(Tfile, line))
    cout << line << endl;  
}


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

请参阅iostate,getline的返回规范和ios运算符bool。

请注意,由于getline返回对您传递的流的引用,因此此循环的惯用格式为:

1
2
3
4
5
ifstream Tfile("player.txt");
string line;
while(getline(Tfile, line)) {
  cout << line << endl;  
}