2011-05-21 31 views
0

所以我提出這個猜測的數字遊戲,在C++中,看起來像這樣:猜數字 - 無限循環不好的時候閱讀

#include <iostream> 
#include <cstdlib> 
#include <ctime> 
using namespace std; 

int main() 
{ 
    srand(time(0)); 
    int secretNumber = rand() % 100 + 1; //Generate "Random number" 
    int nbrOfGuesses = 0; 
    int userInput; 

    cout<<"\t************************************"<<endl; 
    cout<<"\t*         *"<<endl; 
    cout<<"\t*   Guess the number!  *"<<endl; 
    cout<<"\t*         *"<<endl; 
    cout<<"\t************************************"<<endl; 
    cout<<endl; 
    cout << "Try to find the secret int number: " << endl; 

    //While input is good 
    while(cin.good()) 
    { 
     //Do this 
     do { 
      cin>>userInput; 
      nbrOfGuesses++; 

      if (userInput>secretNumber) 
       cout << "Smaller!\n"; 

      else if(userInput<secretNumber) 
       cout << "Bigger!\n"; // <-- Infinite loop here when you enter something other than an integer 

      else //Also using this as a backup of (cin.good()) 
       cout << "Something went wrong with the read"; 
       break; 

     } while(userInput!=secretNumber); 
       cout << "\nCongratulations! You got it in " << nbrOfGuesses << " guesses\n"; 
    } 

    system("pause"); 
    return 0; 
} 

*很抱歉,如果代碼是音符很優雅

正如你可以看到,代碼很有效,直到你輸入一個像'&'或'j'這樣的隨機字符或其他任何不是整數的字符...然後它在cout處循環「Bigger!」;

所以我的問題是:這是什麼原因造成的?

+0

可能重複[循環和嘗試捕捉在壞CIN輸入失敗(http://stackoverflow.com/questions/2292202/while-loop-with-try-catch-fails-at-bad- cin-input) – ildjarn 2011-05-21 00:15:08

回答

7

檢查this post,它是關於同樣的問題。總結:

cin>>userInput; 
if (cin.fail()) { 
    cout<<"Invalid Entry, please try again."<<endl; 
    cin.clear(); 
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
} 

感謝ildjarn指點缺失忽略聲明,我錯過了一部分,即使它在我掛!!後明確提到

+0

我修復了代碼,謝謝指出! :) – user258808 2011-05-21 00:58:55

0

cin >> userInput;

如果它無法讀取integet,則爲cin流設置錯誤位。 你應該檢查並清除後綴。

if (cin.fail()) 
{ 
    cin.clear(); 
    try again 
} 
+1

如果不從輸入緩衝區中刪除無效輸入,調用'clear'有什麼好處呢? – ildjarn 2011-05-21 00:45:48

+0

這是再次嘗試邏輯人! – 2011-05-21 00:49:46

+1

「再試一次」部分從用戶處獲取新輸入。您的答案需要顯示如何首先從緩衝區中首先刪除舊的無效輸入。 – ildjarn 2011-05-21 00:51:00