关于STL中的一种死循环的出现情况

x1001 2003-08-26 07:43:29
//关于STL中的一种死循环出现情况
//程序例程如下:
#include <iostream>
int main()
{
using namespace std;
unsigned int age=0;
while(true)
{
cout<<"请输入年龄:大于0,小于1000:"<<endl;
cin>>age;
if(age<=0 || age>1000)
{
cout<<"输入年龄不正确,请输入范围在0到1000内。"<<endl;
continue;
}
else
break;
}
cout<<"年龄:"<<age<<endl;
return 0;
}
以上,在输入一个比较大的数字时,就是死循环了。我没找到好的解决方法,只想有一种替代方法,如下:
#include <iostream>
int main()
{
using namespace std;
unsigned int age=0;
while(true)
{
cout<<"请输入年龄:大于0,小于1000:"<<endl;
string sv;
cin>>sv;
convert(sv,age); //自定义的一个函数,用来把输入的字串转换为数字,用strtoul()可能也不会达到要求。
if(age<=0 || age>1000)
{
cout<<"输入年龄不正确,请输入范围在0到1000内。"<<endl;
continue;
}
else
break;
}
cout<<"年龄:"<<age<<endl;
return 0;
}
上面这种方法好像比较傻,不知可有高手可有精辟解说,信手解开这个问题?
...全文
50 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
qqchen79 2003-08-27
  • 打赏
  • 举报
回复
No, I guess not. Coz I don't use QQ. :)
x1001 2003-08-27
  • 打赏
  • 举报
回复
感谢各位的答复,qqchen79(知秋一叶 [MS MVP]) 的解答比较简单正确, pengzhenwanli(紫气日盈) 的做法还有一点小小的问题。对了,知秋一叶,你是不是我同学啊?我有个同学的QQ也叫知秋一叶。
答案也得,结贴吧。
qqchen79 2003-08-27
  • 打赏
  • 举报
回复
cout<<"请输入年龄:大于0,小于1000:"<<endl;
cin>>age;
if(!cin.good() || (age<=0 || age>1000)) // <-- check cin before precede
{
cin.clear(); // clear buffer
cout<<"输入年龄不正确,请输入范围在0到1000内。"<<endl;
cout << age << endl;
continue;
}
else {
break;
}
pengzhenwanli 2003-08-27
  • 打赏
  • 举报
回复
你试试下面程序。
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <string>
int main()
{
using namespace std;
unsigned int age=0;
bool bError= false;
while(true)
{
bError = false;
cout<<"请输入年龄:大于0,小于1000:"<<endl;
int ch;
ostringstream buffer;
int oBufferSize = 0;

while((ch = cin.get()) && ch != EOF)
{
if( ch == '\n' )
break;
if( (ch <= '9') && (ch >= '0'))
{
if( oBufferSize >5 )
{
bError = true;
fflush(stdin);
break;
}
buffer << static_cast<char>(ch);
oBufferSize++;
}
else
{
bError = true;
fflush(stdin);
break;
}
}
if( bError)
continue;
buffer << '\0';
istringstream ibuffer(buffer.str());
ibuffer >> age;
if(age<=0 || age>1000)
{
cout<<"输入年龄不正确,请输入范围在0到1000内。"<<endl;
continue;
}
else
break;
}
cout<<"年龄:"<<age<<endl;
return 0;
}
oopig 2003-08-26
  • 打赏
  • 举报
回复
不太明白,怎么就死循环了?
如果是说一直输入错误的数导致不能退出循环的话,完全是使用者的问题。或者你也可以加一个计数判断,比如错误次数超过3就退出。

24,855

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧