c++ stop asking for input on ctrl-d

APorter1031 picture APorter1031 · Dec 2, 2017 · Viewed 7k times · Source

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

Answer

Karina K picture Karina K · Dec 2, 2017

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.