如何讓我的代碼檢測到我按下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