如何在C中检查int或char [英] How to check int or char in c

查看:90
本文介绍了如何在C中检查int或char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将摄氏度转换为华氏度的代码.而且我需要检查什么用户写char或int.

I have a code where I convert celsius to fahrenheit. And I need to check what user writes char or int.

我尝试过isalpha和isdigit,但是它们不起作用.

I've tried isalpha and isdigit, but they do not work.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    char t[] = "";
    scanf("%s", &t);
    if(isalpha(t))
    {
        printf("It's char\n");
    }
    else if (isdigit(t))
    {
        printf("It's int\n");
    }


    return 0;
}

推荐答案

isalpha isdigit 应用于包含char的int类型的对象.

isalpha and isdigit are applied to objects of the type int that contain a char.

您正在尝试将这些函数应用于char *类型的对象(数组类型在表达式中隐式转换为指针类型).

You are trying to apply these functions to an object of the type char * (an array type is implicitly converted to a pointer type in expressions).

此外,数组 t 声明为

char t[] = "";

的大小不足以存储从scanf获得的一个字符,因为它还需要存储终止的零.否则,调用scanf将具有未定义的行为.并且scanf的调用也不正确.

is not enough large to store even one character gotten from scanf because it also need to store the terminating zero. Otherwise a call of scanf will have undefined behavior. And the call of scanf is also incorrect.

scanf("%s", &t);
            ^^^

它的写法至少应像

scanf("%s", t);

您可以声明一个char类型的对象,例如

You could declare an object of the type char like

char t;

然后使用scanf之类的

and then use scanf like

scanf(" %c", &t);

最后

if ( isalpha( ( unsigned char )t ) )
{
    printf("It's char\n");
}
else if ( isdigit( ( unsigned char )t ) )
{
    printf("It's int\n");
}

这篇关于如何在C中检查int或char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆