大侠们帮忙看看

Freedom 2009-05-26 02:04:25
#include <iostream>
using namespace std;
void main()
{
int age;
while(1)
{
cout <<"输入年龄";
cin>>age;
if(cin.fail()) //判断输入的是不是数字
{ cout << "not a number" << endl;
cout << "请从新输入" << endl;
}
else break;
}
} 如果输入的不是数字想让程序从新输入,为什么上面的代码不行,
请各位大侠帮忙指点指点,如果各位大侠还有什么好方法,小弟那是感激不尽
...全文
127 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
wangpingfang 2009-05-26
  • 打赏
  • 举报
回复
试试一楼的方法
weixiaoshashou 2009-05-26
  • 打赏
  • 举报
回复
goto好像已经差不多被别人给遗弃了。
weixiaoshashou 2009-05-26
  • 打赏
  • 举报
回复
你已经跳出了while 了,像一楼那样行。
operatingtuzi 2009-05-26
  • 打赏
  • 举报
回复
同意 一楼 否则fail位还是1
zhangxun2007 2009-05-26
  • 打赏
  • 举报
回复
#include <iostream>
using namespace std;
void main()
{
int age;
while(1)
{
cout < <"输入年龄";
loop: cin>>age;
if(cin.fail()) //判断输入的是不是数字
{ cout < < "not a number" < < endl;
cout < < "请从新输入" < < endl;
goto loop;
}
else break;
}
}
使用goto,强制跳转。
dashuang2006 2009-05-26
  • 打赏
  • 举报
回复
In this example, cin sets the fail bit on the stream when it encounters non-numeric characters. The program clears the fail bit and strips the invalid character from the stream to proceed.

// iostream_cin.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

int main()
{
int x;
cout << "enter choice:";
cin >> x;
while (x < 1 || x > 4)
{
cout << "Invalid choice, try again:";
cin >> x;
// not a numeric character, probably
// clear the failure and pull off the non-numeric character
if (cin.fail())
{
cin.clear();
char c;
cin >> c;
}
}
}

MSDN上面的例子,,建议你装个MSDN或者SDK..这种问题上面都有解答...
lpf000 2009-05-26
  • 打赏
  • 举报
回复
UP
goodname 2009-05-26
  • 打赏
  • 举报
回复

#include <iostream>
using namespace std;

void main()
{
int age;
while(1)
{
cout <<"输入年龄";
cin>>age;
if(cin.fail()) //判断输入的是不是数字
{
cout << "not a number" << endl;
cout << "请从新输入" << endl;

cin.clear();//加上这两句,可以清除错误标记,并清空缓冲区内容。
cin.ignore();
}
else break;
}
}

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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