| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 5839 人关注过本帖
标题:如何判断输入的变量的类型(C和C++)(有源码)
只看楼主 加入收藏
写在人生边上
Rank: 1
等 级:新手上路
帖 子:35
专家分:0
注 册:2007-11-8
收藏
 问题点数:0 回复次数:4 
如何判断输入的变量的类型(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");
}
搜索更多相关主题的帖子: 变量 源码 类型 int 
2008-03-21 22:01
now
Rank: 1
来 自:广州
等 级:新手上路
帖 子:544
专家分:0
注 册:2007-11-9
收藏
得分:0 
对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]]
2008-03-22 23:04
写在人生边上
Rank: 1
等 级:新手上路
帖 子:35
专家分:0
注 册:2007-11-8
收藏
得分:0 
程序进入死循环
我若改成如下代码,当输入 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");
}
2008-05-03 15:27
StarWing83
Rank: 8Rank: 8
来 自:仙女座大星云
等 级:贵宾
威 望:19
帖 子:3951
专家分:748
注 册:2007-11-16
收藏
得分:0 
while(scanf("%d",&j)!=1)
    {
        while(getchar()!='\n');
        printf("The type of the data you input unmatches!\n");
        printf("Please input the data again:");
    }

专心编程………
飞燕算法初级群:3996098
我的Blog
2008-05-03 16:03
我是小菜乃哦
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2014-7-20
收藏
得分:0 
定义一个整型变量c,将其初始化,判断是否是数字。输出Y或N,并将其输出注意输入使用scanf输入
 求指
2014-07-20 19:37
快速回复:如何判断输入的变量的类型(C和C++)(有源码)
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.018774 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved