Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ stop asking for input on ctrl-d

Tags:

c++

getline

input

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? ";
}
like image 742
APorter1031 Avatar asked Dec 14 '22 19:12

APorter1031


1 Answers

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.

like image 80
Karina Kozarova Avatar answered Dec 31 '22 13:12

Karina Kozarova