0

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)

daniel
  • 83
  • 6
  • You should avoid the attempt to use eof() in the loop because of this: [https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – drescherjm Aug 03 '20 at 17:30
  • looking as *is* flags – bruno Aug 03 '20 at 17:30
  • better yet, just check if `is == false` – Cássio Renan Aug 03 '20 at 17:30
  • @drescherjm what do you mean? I want to exit the loop when I reach the end of file – daniel Aug 03 '20 at 17:30

2 Answers2

5

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")
NathanOliver
  • 150,499
  • 26
  • 240
  • 331
2
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.

john
  • 71,156
  • 4
  • 49
  • 68