我已經編寫了一個關於猜測密碼的代碼,但是當給出一個字母字符作爲輸入而不是一個整數時,我遇到了一個問題。它停止了這個程序。我該如何抵制這個問題。如果在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;
代碼不能編譯。向我們展示實際代碼。 (如果第一個字符是?) – Incomputable
如果給出無效輸入後的輸入流,則必須使用'cin.clear()'來重置失敗狀態。 –
查看'continue'關鍵字 –