检测击中C ++中的Enter键 [英] Detect hitting Enter Key in C++

查看:90
本文介绍了检测击中C ++中的Enter键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取我的代码以检测到我按下Enter键?我尝试使用cin.get()并没有成功.同样,当按下回车键时,我想将布尔值x从true更改为false.

How can I get my code to detect me hitting the enter key? I tried using cin.get() without any success. Also when the enter key is pressed, I'd like to change a boolean x from true to false.

为什么这行不通?

if (cin.get() == '\n'){
x = false;
}

当我按下回车键(请参见下面的代码)时,我想结束循环(因此结束程序)

I'd like to end my loop (and thus and the program) when the enter key is pressed (see code below)

所有代码(简单的石头,纸,剪刀游戏):

All code (simple rock, paper, scissors game):

#include <iostream>
#include <string>
#include <cstdlib> //random
#include <time.h> //pc time

using namespace std;

int main()
{

    string rpsYou;
    string rpsCom;
    string winner;
    bool status = true;

while (status){
    cout << "Welcome to Rock, Scissors, Paper!\nYou'll have to compete against the computer."
            " Please enter 'Rock', 'Paper' or 'Scissors' here: ";
    cin >> rpsYou;

    //Random number
    srand (time(NULL));
int randomNum = rand() % 4; //  -> (rand()%(max-min))+min;

//Computers guess
if (randomNum ==1){
    rpsCom = "Rock";
}
else if (randomNum ==2){
    rpsCom = "Paper";
}
else {
    rpsCom = "Scissors";
}

//First letter to capital
rpsYou[0] = toupper(rpsYou[0]);

if (rpsYou == "Rock" || rpsYou == "Paper" || rpsYou == "Scissors"){

    cout << "You: " << rpsYou << "\nComputer: " << rpsCom << "\n";

}
else {
    cout << "ERROR: Please enter 'Rock', 'Paper' or 'Scissors'.";
}


if ( (rpsYou == "Rock" && rpsCom == "Rock") ||
     (rpsYou == "Paper" && rpsCom == "Paper") ||
     (rpsYou == "Scissors" && rpsCom == "Scissors") ){

    cout << "Tie :|";

}
else if( (rpsYou =="Rock" && rpsCom =="Scissors") ||
         (rpsYou =="Paper" && rpsCom =="Rock") ||
         (rpsYou =="Scissors" && rpsCom =="Paper")){
    cout << "Congratulations! You won! :)";
}

else{
    cout << "Oh no! You lost! :(";
}

}

    return 0;
}

推荐答案

您可以这样做:

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

这是假设用户输入中没有任何内容(即:用户只需按Enter键即可)

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

这篇关于检测击中C ++中的Enter键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆