2014-02-18 84 views
1
#include<iostream> 
#include<cstdlib> 
#include<ctime> 
#include<string> 

using namespace std; 

int main() 
{ 
    char replay; 
    int userInput; 
    cout<< "Let's play Rock, Paper, Scissors"<<endl; 
    do 
{ 
    cout<<"Enter 1 for Rock, 2 for Paper, 3 for Scissors"<< endl; 
    cin>> userInput; 

    switch(userInput) 
    { 
     case 1: 
     cout <<"You chose rock" << endl; 
     break; 

     case 2: 
     cout <<"You chose paper" <<endl; 
     break; 

     case 3: 
     cout <<"You chose scissors" << endl; 
     break; 

     default: 
     cout << userInput << " is not a valid choice"<< endl; 
     break; 
    } 
    cout<<"Would you like to play again (Y for yes, N for no)?"<<endl; 
    cin >> replay; 
} while((replay=='Y') || (replay=='y')); 

    return 0; 

} 

當我在輸入數字的回答中輸入一個字符時,當我被問及是否要再次玩時,輸入的字符不是Y,Y,N或n時,進入無限循環爲什麼我的程序在輸入字符時會出現無限循環?

+0

你在使用,因爲我不能複製VS2010下,即使是在HTTP編譯:// ideone .COM/C88qG3? – herohuyongtao

+0

@herohuyongtao g ++和我在終端 – user2988803

回答

3

userInput定義爲int。當您嘗試讀取int時,流中的實際內容是char,它將失敗(但char仍在緩衝區中)。您必須清除錯誤狀態,而忽略壞的輸入:

if (!(cin >> userInput)) 
{ 
    cin.clear(); // clears the error state 
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // remove the bad input from the buffer 
} 
else 
{ 
    // the code if the input was valid 
} 
+0

這樣做我還沒有走這麼遠到編碼在我的代碼中使用此代碼。我只是需要知道我的循環在哪裏,所以我可以修復它 – user2988803

+1

**是**是什麼導致你的無限循環。你有無效的輸入,所以當你做while的條件時,它不會停止循環,將它發送到循環的頂部,輸入已經在緩衝區中,所以它重複...永遠。 –

+0

如果我聲明userInput爲「char userInput」,我仍然得到一個無限循環 – user2988803

1

只是一個建議,但如下我會重新安排你的代碼:

#include<iostream> 
#include<cstdlib> 
#include<ctime> 
#include<string> 

using namespace std; 

int main() 
{ 
    char replay; 
    char userInputChar; 
    int userInput; 
    cout<< "Let's play Rock, Paper, Scissors"<<endl; 
    for(;;) 
    { 
     cout << "Enter 1 for Rock, 2 for Paper, 3 for Scissors"<< endl; 
     cin >> userInputChar; 

     userInput = userInputChar - '0'; 

     switch(userInput) 
     { 
      case 1: 
      cout <<"You chose rock" << endl; 
      break; 

      case 2: 
      cout <<"You chose paper" <<endl; 
      break; 

      case 3: 
      cout <<"You chose scissors" << endl; 
      break; 

      default: 
      cout << userInput << " is not a valid choice"<< endl; 
      break; 
     } 
     cout<<"Would you like to play again (Y for yes, N for no)?"<<endl; 
     cin >> replay; 

     if((replay!='Y') || (replay!='y')) 
      break; 
    } 

    return 0; 

} 

注意我是如何帶着char輸入轉換爲照顧一個int

如果你想用你的電流回路聲明userInput作爲char,然後讓你的switch語句是這樣的:switch(userInput - '0')

+0

我還沒有深入到編碼中去在我的代碼中使用這段代碼。我只需要知道我的循環在哪裏,所以我可以修復它 – user2988803

+0

@ user2988803查看我的更新。 – turnt

+0

我做了編輯,但我無法退出程序後,它問我,如果我想再次玩...就像我會輸入N或N,我不能退出程序 – user2988803

相關問題