如何让我的代码检测到我按下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;
}
可以显示所有的代码,请。 – kodaman 2014-10-12 14:06:01
好吧,我会添加所有的代码 – Dipsy 2014-10-12 14:07:15
这可能会有所帮助。 http://msdn.microsoft.com/en-us/library/ms171538(v=vs.110).aspx – kodaman 2014-10-12 14:27:14