急救,这个判断变量类型的代码哪里错了。

rossi789 2006-01-24 10:20:06
我输入5,它居然说有错,我输入字符型数据它却滚屏提示有错,而不返回到cin>>a等待我重新输入。不知道错在哪里
#include <iostream.h>
#include <typeinfo>
main()
{
int a;
for(;;)
{
cin>>a;
if(typeid(a).name()=="int")
{
cout<<"输入正确"<<endl;
break;
}
else cout<<"输入有误,请重新输入"<<endl;
}
}
...全文
261 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
feeboby 2006-01-25
  • 打赏
  • 举报
回复
dev c++ 4.9.8.0

#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <typeinfo>
using namespace std;

int main(int argc, char *argv[])
{

float a;
for(;;)
{
cin>>a;
if(typeid(a) == typeid(int))
{
cout<<"输入正确"<<endl;
break;
}
else cout<<"输入有误,请重新输入"<<endl;
}
system("PAUSE");
return 0;
}
rossi789 2006-01-25
  • 打赏
  • 举报
回复
到底该怎么搞阿
rossi789 2006-01-25
  • 打赏
  • 举报
回复
算了..
kikikind 2006-01-25
  • 打赏
  • 举报
回复
楼上说得对呀~~~
rossi789 2006-01-25
  • 打赏
  • 举报
回复
还是不行,运行结果不对。我输入一个字符它滚屏出错了。http://img235.photo.163.com/13957176484/29127375/755226585.jpg
我想是不是由于这个方法行不通。typeid是测试变量类型的,a开始已经定义成int的话,后面不管再输入其他类型的数据,typeid是不判断输入的值的类型的,依旧判断的是变量本身的类型。
rossi789 2006-01-24
  • 打赏
  • 举报
回复
那怎么在你的VC里面可以的阿,dev就是不行.我把void去了,加了就通不过编译.运行结果还是不行.看我截的图
http://img235.photo.163.com/13957176484/29127375/753872153.jpg
feeboby 2006-01-24
  • 打赏
  • 举报
回复
不用包含这个头文件
rossi789 2006-01-24
  • 打赏
  • 举报
回复
dev里面怎么没有stdafx.h这个头文件?
rossi789 2006-01-24
  • 打赏
  • 举报
回复
奇怪,我在DEV-C++里连编译都通不过
guoxiaoli 2006-01-24
  • 打赏
  • 举报
回复
typeid(a).name()=="int"

字符串比较函数:strcmp(typeid(a).name() , "int") == 0

typeid(a)

The result of a typeid expression is a const type_info&. The value is a reference to a type_info object that represents either the type-id or the type of the expression, depending on which form of typeid is used.

name()

const char* name() const;这是函数原形。他的返回只是一个长字符串指针。

所在和"int"比较时会报错!


这是MSDN的内容
把报错的信息拿出来看看
feeboby 2006-01-24
  • 打赏
  • 举报
回复
我的行
vc6

#include "stdafx.h"
#include <string.h>


#include <iostream.h>
#include <typeinfo>
void main()
{
int a;
for(;;)
{
cin>>a;
if(strcmp(typeid(a).name() , "int") == 0)
{
cout<<"输入正确"<<endl;
break;
}
else cout<<"输入有误,请重新输入"<<endl;
}
}
rossi789 2006-01-24
  • 打赏
  • 举报
回复
试过了不行阿
feeboby 2006-01-24
  • 打赏
  • 举报
回复
把if(typeid(a).name()=="int")改成
if(strcmp(typeid(a).name() , "int") == 0)

64,637

社区成员

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

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