[英]how to allow multiple inputs in case of an incorrect data type entry in cpp?
我有一個程序,它生成隨機數,並要求用戶繼續猜測,直到他/她正確。 即使我通過處理錯誤情況錯誤地輸入任何其他數據類型,我希望它繼續接受新值。
我的問題是,當我試圖運行下面的程序時,一旦我輸入一個字符並按下回車,它就進入一個無限循環。 我嘗試使用cin.ignore()和cin.clear(),但這只是讓程序在第一次輸入后停止。
誰能幫助我了解正在發生的事情以及如何實現所需的輸出? 提前致謝。
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
int secret_num, guess;
srand(time(NULL));
secret_num=rand() % 101 + 0;
cout<<"Enter your guess between 0 and 100: ";
do
{
if(!(cin>>guess))
{
cout<<" The entered value is not an integer"<<endl;
}
else if( isnumber(guess))
{
if(guess>secret_num)
cout<<"Too high";
else if(guess<secret_num)
cout<<"too low";
cout<<endl;
}
}
while(secret_num!=guess);
if((guess==secret_num)| (isnumber(guess)))
{
cout<<"yes the correct number is "<<secret_num<<endl;
}
return 0;
}
編輯:這是我的代碼中cin.clear()和cin.ignore(1000,'\\ n')輸出的截圖,當我在輸入字符兩次后輸入數字時。
if (!(cin >> guess))
{
cout << " The entered value is not an integer" << endl;
cin.clear(); // clear must go before ignore
// Otherwise ignore will fail (because the stream is still in a bad state)
cin.ignore(std::numeric_limits<int>::max(), '\n');
}
默認情況下,cin.ignore將忽略單個字符。 如果他們輸入超過1個字符,那就不夠了,這就是為什么我對它進行了一些修改。
if ((guess == secret_num) | (isnumber(guess)))
|
是一個按位運算符[OR]
||
是邏輯運算符[OR]
但我認為你真正想要的是&&
(AND)
if ((guess == secret_num) && (isnumber(guess)))
有幾個問題。
您應該使用cin.clear()
和cin.ignore()
作為@José建議。
什么是isnumber()
? 我猜它正在返回false
所以沒有提示信息(即“太高”和“太低”)被打印出來,看起來它停止了,雖然它只是在等待下一個輸入。 並且isnumber()
對我沒有意義。 guess
已經被聲明為一個int
,它必須是一個數字,不是嗎?
if((guess==secret_num)| (isnumber(guess)))
在這里是不必要的。 在用戶輸入正確的數字之前,循環不會結束,這個條件應該已經得到滿足。
你可以使用clear和flush
if(!(cin>>guess))
{
cout<<" The entered value is not an integer"<<endl;
cin.clear();
fflush(stdin);
}
如果您從控制台讀取,則此方法有效。 否則你可以和@José一起回答。
我會改變循環中的邏輯,因為有一些無用的測試。 這對我有用:
#include <iostream>
#include <limits>
#include <cstdlib> // You may take a look at <random> and <chrono>
#include <time.h>
using std::cout;
using std::cin;
int main() {
srand(time(NULL));
int secret_num = rand() % 101;
cout << secret_num << '\n';
cout << "Enter your guess between 0 and 100:\n";
int guess = -1;
do {
cin >> guess;
if ( cin.eof() )
break;
if ( cin.fail() ) {
cout << "The entered value is not an integer, please retry.\n";
// clear the error flag
cin.clear();
// ignore the rest of the line
cin.ignore(std::numeric_limits<int>::max(),'\n');
// clear the value of the variable
guess = -1;
continue;
}
// now we know that guess is a number
if ( guess > secret_num )
cout << "Too high\n";
else if ( guess < secret_num )
cout << "Too low\n";
else {
cout << "Yes the correct number is " << secret_num << std::endl;
break;
}
} while ( true );
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.