2014-10-12 104 views
1

如何让我的代码检测到我按下Enter键?我尝试使用cin.get()没有任何成功。另外,当按下回车键时,我想将布尔值x从true更改为false。在C++中检测到输入密钥

为什么不能正常工作?

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

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

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

#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; 
} 
+0

可以显示所有的代码,请。 – kodaman 2014-10-12 14:06:01

+0

好吧,我会添加所有的代码 – Dipsy 2014-10-12 14:07:15

+0

这可能会有所帮助。 http://msdn.microsoft.com/en-us/library/ms171538(v=vs.110).aspx – kodaman 2014-10-12 14:27:14

回答

2

你可以这样做:

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

这是假设没有什么在用户输入,(即:用户只需简单地按下回车)

+0

谢谢,但我必须在哪里放置该代码? – Dipsy 2014-10-12 14:42:12

+1

你可以用'getline(cin,rpsYou)'替换'cin >> rpsYou;'在你的'while循环中'并且在你接收到用户的代码后添加'if(input ==“”){status = false;}'输入。 (例如:在这行上面添加'else if'语句:'else {cout <<“错误:请输入'Rock','Paper'或'Scissors'。”;}') – Edwin 2014-10-12 14:45:47

0

听起来就像你在“实时”获取按键,就像在游戏中可能有用。但cin不能像那样工作。在标准C++中没有办法“检测用户何时按下输入”!所以当用户按下输入时你不能结束程序。你可以做的是当用户输入空行或者当用户输入例如“退出”(或者任何,取决于你)时结束程序,但是每个用户输入都必须以按回车结束。

cin读取就像从文本文件中读取,除了每次用户按下输入时此文本文件都会获取新行。所以最接近检测用户按下回车使用std::getline

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

这将让来自标准输入所有的字符,直到一个新行(或到文件结束),这通常意味着用户按下进,什么时候该使用在控制台应用程序中。请注意,实际的行尾不会存储在字符串中,因此如果用户只是按下回车键而不输入其他字符,则line将为空字符串。


望着编辑后的问题,你可以用getline(cin, rpsYou);取代cin >> rpsYou;。您可能还想要添加trimming您读取的字符串,以防用户输入额外空格。

0

您无法检测到在标准C++中按了哪个键。它依赖于平台。这是一个类似的question,可能会帮助你。