user14043526
user14043526

Reputation:

C++ how to detect eof using getline()

There are some variations of this question but none exactly matches what I'm looking for.

Giving the following code:

string command="";

while (command.compare("quit")!=0)
{
    os << prompt;
    getline(is,command);
}

How may I detect if getline reached eof (end of file)

Upvotes: 0

Views: 223

Answers (2)

NathanOliver
NathanOliver

Reputation: 181057

getline returns a reference to the stream you pass to it, and that stream will evaluate to false if it hits a failure state. Knowing that, you can leverage that to move getline into the condition for the while loop so that if it fails, then the condition will be false and the loop stops. You can combine that will your check for quit as well like

while (getline(is,command) && command != "quit")
{
    // stuff
}

You can also add the prompt to the loop like

while (os << prompt && getline(is,command) && command != "quit")

Upvotes: 5

john
john

Reputation: 88027

while (command.compare("quit")!=0)
{
    os << prompt;
    getline(is,command);
    if (is.eof())
         do something at end of file
}

But note that is reaching end of file does not mean that there isn't something in command. You can read data and reach the end of file at the same time.

What you might be looking for instead is this

os << prompt;
while (getline(is,command) && command != "quit")
{
    do something with command
    os << prompt;
}

That code will quit the loop if you reach end of file and nothing has been input, or if 'quit' is input.

Upvotes: 2

Related Questions