注册 登录
编程论坛 C++教室

如何判断输入的变量的类型?

写在人生边上 发布于 2008-03-21 22:44, 798 次点击
我定义一个 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");
}
2 回复
#2
peach54602008-03-21 23:11
貌似cin>>a(假如a是int)在输入字母的时候会抛出异常的...截获这个异常处理应该可以
#3
aipb20072008-03-22 00:14
不是异常,是流状态

去看看标准IO库的内容吧
1