简体   繁体   English

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

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

I've just started to work with files in C++ and i'm still new to how file objects and getline() work. 我刚刚开始使用C ++处理文件,但是我仍然对文件对象和getline()的工作方式还不熟悉。

So I sort of understand the getline() function and how it works and that it returns a Boolean via the void* when used in a Boolean context but what i don't understand is why in the code the while loop doesn't result in an infinite loop or an error because there aren't any statements that would terminate the loop such as a break. 所以我有点了解getline()函数及其工作原理,并且在布尔上下文中使用它会通过void *返回一个布尔值,但是我不明白的是为什么在代码中while循环不会导致无限循环或错误,因为没有任何语句可以终止循环,例如break。 Any help would be much appreciated thank you! 任何帮助将不胜感激,谢谢!

The only thing that i could particularly think of was that the when getline() does its operations and works through each line it actively changes the status of while(Tfile) and when the end of the file is reached while(Tfile) is no longer true which results in the termination of the loop but i'm not too sure. 我唯一想到的就是getline()何时执行其操作并遍历每一行,它会主动更改while(Tfile)的状态,以及何时到达文件末尾while(Tfile)不再true,这会导致循环终止,但我不太确定。

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

getline sets the eofbit of Tfile when it reaches the End Of File. getline设置Tfile到达文件Tfile时的eofbit This causes the operator bool of Tfile to evaluate to false, which then terminates your loop. 这会使Tfileoperator bool评估为false,从而终止循环。

See iostate , getline's return specification , and ios operator bool . 请参见iostategetline的返回规范ios运算符bool

Notice that since getline returns a reference to the stream you passed it, the idiomatic form of this loop is: 注意,由于getline返回对您传递的流的引用,因此此循环的惯用格式为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM