-3

我已經編寫了一個關於猜測密碼的代碼,但是當給出一個字母字符作爲輸入而不是一個整數時,我遇到了一個問題。它停止了這個程序。我該如何抵制這個問題。如果在C++中給用戶輸入一個字母表時如何重新啓動循環

srand(time(0)); 
int a,secret; 
secret=rand() % 10 +3; 
do{ 
     cout<<"Guess the secret num between 1-10 + 3 : "; 
cin>>a; 
else if(a>secret) 
{ 
    cout<<"Secret num is smaller!!"<<endl; 
} 
else if(a<secret) { 
    cout<<"Secret num is greater !!"<<endl; 
} 

} 
while(a!=secret) 
cout<<" "<<endl; 
cout<<""<<endl; 
    cout<<"Congratulations!!!! This is the secret num...."<<secret<<endl; 
+6

代碼不能編譯。向我們展示實際代碼。 (如果第一個字符是?) – Incomputable

+0

如果給出無效輸入後的輸入流,則必須使用'cin.clear()'來重置失敗狀態。 –

+0

查看'continue'關鍵字 –

回答

0

你沒有,但如果你仍然想解決的問題,您可以流線並獲得唯一的號碼的線路。

Answered by Jesse Good here

我會用std::getlinestd::string讀取整個行 ,然後只跳出循環的時候可以將整個 線轉換爲雙。

#include <string> 
#include <sstream> 

int main() 
{ 
    std::string line; 
    double d; 
    while (std::getline(std::cin, line)) 
    { 
     std::stringstream ss(line); 
     if (ss >> d) 
     { 
      if (ss.eof()) 
      { // Success 
       break; 
      } 
     } 
     std::cout << "Error!" << std::endl; 
    } 
    std::cout << "Finally: " << d << std::endl; 
} 
0

在你的情況,因爲0是在允許範圍之外,這是非常簡單的:

  1. 初始化a爲0,如果a解壓後是0:
  2. clearcin
  3. ignorecin(小心指定要忽略換行符性格:Cannot cin.ignore till EOF?

您的最終代碼應該是這個樣子:

cout << "Guess the secret num between 1-10 + 3 : "; 
cin >> a; 

while (a != secret) { 
    if (a == 0) { 
     cin.clear(); 
     cin.ignore(std::numeric_limits<streamsize>::max(), '\n'); 
     cout << "Please enter a valid number between 1-10 + 3 : "; 
    } 
    else if (a < secret) { 
     cout << "Secret num is smaller!!\nGuess the secret num between 1-10 + 3 : "; 
    } 
    else if (a < secret) { 
     cout << "Secret num is greater !!\nGuess the secret num between 1-10 + 3 : "; 
    } 
    a = 0; 

    cin >> a; 
} 

Live Example

相關問題