我有一个程序会生成随机数,并要求用户不断猜测它,直到他/她正确为止。我希望它继续接受新值,即使我通过处理错误情况错误地输入了任何其他数据类型也是如此。
我的问题是,当我尝试运行以下程序时,一旦我输入一个字符并按Enter键,它将进入无限循环。我尝试使用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)))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句