Search code examples
ccharscanfdigitsisalpha

How to check int or char in c


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

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;
}

Solution

  • isalpha and isdigit are applied to objects of the type int that contain a 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).

    Moreover the array t declared like

    char t[] = "";
    

    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);
                ^^^
    

    It should be written at least like

    scanf("%s", t);
    

    You could declare an object of the type char like

    char t;
    

    and then use scanf like

    scanf(" %c", &t);
    

    and at last

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