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