Detect hitting Enter Key in C++

橙三吉。 提交于 2019-12-06 19:56:26

You could do:

cout << "Hit enter to stop: ";
getline(cin, rpsYou);
if (input == "") {
    status=false;
}

This is assuming there's nothing in the user input, (i.e: the user just simply presses enter)

devil0150

You can't detect what key was pressed in standard C++. It's platform dependent. Here is a similar question that might help you.

hyde

Sounds like you are thinking of getting key presses "in real time", like might be useful in a game for example. But cin does not work like that. There is no way to "detect when user presses enter" in standard C++! So you can not end the program when user presses enter. What you can do is end the program when user enters empty line, or when user enters for example "quit" (or whatever, up to you), but every user input must end in them pressing enter.

Reading from cin is just like reading from a text file, except this text file gets a new line every time user presses enter. So closest thing to detecting user pressing enter is using std::getline:

std::string line
std::getline(std::cin, line);

This will get all characters from stdin until a newline (or until end of file), which usually means user pressed enter, when this is used in a console application. Note that the actual end-of-line will not be stored in the string, so if user just pressed enter without typing anything else, line will be empty string.


Looking at question after edit, you could replace cin >> rpsYou; with getline(cin, rpsYou);. You might then also want to add trimming the string you read, in case user for example typed extra spaces.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!