6

I am trying to read user input until ctrl-d is hit. If I am correct, ctrl+d emits an EOF signal so I have tried checking if cin.eof() is true with no success.

Here is my code:

string input;
cout << "Which word starting which year? ";
while (getline(cin, input) && !cin.eof()) {
    cout << endl;
    ...
    cout << "Which word starting which year? ";
}
Karina Kozarova
  • 1,145
  • 3
  • 14
  • 29
APorter1031
  • 2,107
  • 6
  • 17
  • 38

1 Answers1

14

So you want to read until EOF, this is easily achieved by simply using a while loop and getline:

std::string line; 
while (std::getline(std::cin, line))
{
    std::cout << line << std::endl;
}

Here using getline(getline returns the input stream) you get the input, if you press Ctrl+D, you break out of the while loop.

It's inportant to note that EOF is triggered different on Windows and on Linux. You can simulate EOF with CTRL+D (for *nix) or CTRL+Z (for Windows) from command line.

Keep in mind that you might exit the loop in other conditions too - std::getline() could return a bad stream for some failures and you might want to consider handling those cases too.

Karina Kozarova
  • 1,145
  • 3
  • 14
  • 29
  • I believe `std::endl` is superfluous here, as flushing the stream is not needed. May be it could be good old `'\n'`? endl is a source of performance problems – Incomputable Dec 02 '17 at 20:38
  • 5
    @Incomputable that is a premature optimization. – bolov Dec 02 '17 at 20:43
  • `std::getline()` could return a bad stream for other kinds of failure, too (but EOF is most likely if `std::cin` is connected to a terminal). – Toby Speight Feb 21 '20 at 12:01
  • A piece of information that may help some landing on this question: getting the EOF character breaks out of the loop because it completely closes stdin for this program. Any subsequent similar loop won't be entered at all. – foxesque May 12 '22 at 17:45