2014-10-12 66 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,可能會幫助你。