这一小段判断c是不是数字的vc++代码为什么不行?郁闷啊!!

来源:百度知道 编辑:UC知道 时间:2024/05/13 11:43:10
for (bool an = false; !an;)
{
cin>>c;
if(c>='0' && c<='9')
{
an = true;
}
else
cout<<"please enter a number!"<<endl;
}

大家帮帮忙啊.........
我更希望实现c是任何数字时都可以继续(10以上也行)
这个代码如果不输数字 就会不断显示please enter a number无数遍!!
帮忙改改把..
忘了说了 如果输入不是数字要在输入一次
ps:277827785兄 你那段程序还是不行........

如果能完全解决 (代码+说明)
追加30分

#include <iostream>
#include <limits>
using namespace std;

int main()
{
int c;
while (!(cin>>c))//读取字符直到cin为true
{
cout<<"please enter a number!"<<endl;
cin.clear();//清除输入流错误状态
cin.ignore(numeric_limits<streamsize>::max(), '\n');//清除输入缓冲区数据
}
cout<<c;
return 0;
}

你的问题就在读取非数字字符以后没有清除输入缓冲区,缓冲区仍有原来的错误数据,因此cin>>c读到的始终是错误的数据,成为死循环,也就不断的显示please enter a number了。

for (bool an = false; !an;)
{
cin>>c;
do
{
cout<<"please enter a number!"<<endl;
}
while(c<'0'&&c>='9')
if(c>='0' && c<='9')
{
an = true;
}
else
break;
}