c++ stop asking for input on ctrl-d
Asked Answered
H

1

7

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? ";
}
Hazlett answered 2/12, 2017 at 20:19 Comment(0)
B
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.

Brahmaputra answered 2/12, 2017 at 20:26 Comment(4)
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 problemsLeesa
@Leesa that is a premature optimization.Loesceke
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).Swarey
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.Preliminaries

© 2022 - 2024 — McMap. All rights reserved.