cin时遇到的问题-----不明白为什么会是这样

Beover1984 2003-10-19 09:19:08
#include<stdlib.h>
#include<iostream>

using namespace std;

template<class T>
bool Input( T &a )
{
int cnt = 0;
while( cnt < 3 )
{
cin>> a;
if( a < 0 )
cout<< "the number less-than 0,illegal!\n";
else
return true;
++cnt;
}
return false;
};


int main()
{
int a = 0;
bool res = false;
res = Input( a );
if( res ) cout<< a;
system ( "pause" );
}

测试结果:

a
0请按任意键继续 . . .



-1
the number less-than 0,illegal!
a
the number less-than 0,illegal!
the number less-than 0,illegal!
请按任意键继续 . . .

请各位看一下,谢谢了
...全文
47 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Beover1984 2003-10-19
  • 打赏
  • 举报
回复
楼上的意思我明白了,谢谢!
Beover1984 2003-10-19
  • 打赏
  • 举报
回复
楼上的意思
mimocrys 2003-10-19
  • 打赏
  • 举报
回复
A定义的是INT型
输入类型不匹配造成CIN流无法使用
可以使用cin.clear()清除cin流中的违法输入,直到遇到一个正确字符为止
函数可以改写如下:
#include<stdlib.h>
#include<iostream>

int testcin(int x);

using namespace std;

template<class T>
bool Input( T &a )
{
int cnt = 0;
while( cnt < 3 )
{
//cin>> a;
a=testcin(a);
if( a < 0 )
cout<< "the number less-than 0,illegal!\n";
else
return true;
++cnt;
}
return false;
};


void main()
{
int a = 0;
bool res = false;
res = Input( a );
if( res ) cout<< a;
system ( "pause" );
}

int testcin(int x)

{

cin>>x;

while(!cin)//输入不匹配
{
cout<<"输入不匹配原有类型,请重新输入:\n";
cin.clear();//重置输入法状态
while (cin.get()!='\n')// 跳过输入流中已有的内存
{
continue;
}
cin>>x;
}

return x;
}



point_to 2003-10-19
  • 打赏
  • 举报
回复
什么意思??
用vc6好好的啊!!

69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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