2

I've just started to work with files in C++ and i'm still new to how file objects and getline() work.

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. 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.

ifstream Tfile("player.txt");
string line;
while(Tfile){
        if (getline(Tfile, line))
    cout << line << endl;   
}
DarkX
  • 31
  • 3
  • 1
    related: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – NathanOliver Jan 22 '19 at 21:58
  • 1
    You should start from understanding that `getline` returns no boolean, and no `void*`, but a reference to the stream. – SergeyA Jan 22 '19 at 21:59
  • Why do you think "getline() end's the while loop"? The condition of while appears to be Tfile. – 2785528 Jan 22 '19 at 22:13
  • DarkX, consider selecting your *ahem* favorite answer as the accepted answer to this question. – okovko Jan 22 '19 at 22:37

1 Answers1

6

getline sets the eofbit of Tfile when it reaches the End Of File. This causes the operator bool of Tfile to evaluate to false, which then terminates your loop.

See iostate, getline's return specification, and ios operator bool.

Notice that since getline returns a reference to the stream you passed it, the idiomatic form of this loop is:

ifstream Tfile("player.txt");
string line;
while(getline(Tfile, line)) {
  cout << line << endl;   
}
okovko
  • 1,485
  • 8
  • 21