如何判断输入的变量的类型(C和C++)(有源码)
我定义一个 int 型的变量,当我输入一个字符(例如:字母'A'等等),我希望这个时候程序提示我:“你输入的变量的类型与您定义的变量的类型不匹配!请重新输入:”。
我希望能用C和C++语言实现上述功能。
我分别用C和C++写了代码,但是都有问题。请高手指点,我在此先谢过了!
代码一:
#include <stdlib.h>
#include <iostream.h>
#include <typeinfo.h>
void main()
{
int i,t;
cout<<typeid(i).name()<<endl;
cout<<"Please input the data:";
cin>>i;
if(typeid(i).name()=="int")
{
t=0;
cout<<"1234";
}
else
{
t=1;
cout<<"5678";
}
while(t)
{
printf("The type of the data you input unmatches!\n");
printf("Please input the data again:");
cin>>i;
if(typeid(i).name()=="int")
t=0;
else
t=1;
}
system("pause");
}
代码二:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
void main()
{
int j;
printf("Please input the data:");
scanf("%d",&j);
if(isalpha(j))
{
printf("The type of the data you input unmatches!\n");
printf("Please input the data again:");
scanf("%d",&j);
}
printf("\n");
system("pause");
}
----------------解决方案--------------------------------------------------------
对C代码:
当输入字母A时,scanf("%d",&j);由于A不是数值,scanf将会把A放回缓冲区,并不会将A读入到变量j 中;所以isalpha(j)中的j由于之前没有初始化,是一个垃圾值,当输入字母时只会出错。
可将if语句改为while(scanf("%d",&j)!=1), 并删除上下两句scanf语句。
[[it] 本帖最后由 now 于 2008-3-22 23:07 编辑 [/it]]
----------------解决方案--------------------------------------------------------
程序进入死循环
我若改成如下代码,当输入 a回车 时,程序进入死循环,怎么解决呢?#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
void main()
{
int j;
printf("Please input the data:");
while(scanf("%d",&j)!=1)
{
printf("The type of the data you input unmatches!\n");
printf("Please input the data again:");
}
printf("\n%d",j);
printf("\n");
system("pause");
}
----------------解决方案--------------------------------------------------------
while(scanf("%d",&j)!=1)
{
while(getchar()!='\n');
printf("The type of the data you input unmatches!\n");
printf("Please input the data again:");
}
----------------解决方案--------------------------------------------------------