【发布时间】:2016-02-15 06:25:34
【问题描述】:
我有一个程序可以生成随机数并要求用户继续猜测,直到他/她猜对为止。即使我通过处理错误情况错误地输入了任何其他数据类型,我也希望它继续接受新值。
我的问题是,当我尝试运行以下程序时,只要我输入一个字符并按 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') 时输出的屏幕截图,当我在输入字符两次后输入数字时。
【问题讨论】:
-
什么是
isnumber()?
标签: c++