DarkX
DarkX

Reputation: 31

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.

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;   
}

Upvotes: 2

Views: 1169

Answers (1)

okovko
okovko

Reputation: 1911

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;   
}

Upvotes: 7

Related Questions