Check if a char is a digit? (in C)

前端 未结 2 652
北海茫月
北海茫月 2020-12-22 04:01

NOTE THAT I AM A NEWBIE

I\'ve used isdigit() function before, but now I have an issue:

I need to check if (for an example) a

2条回答
  •  情话喂你
    2020-12-22 04:24

    The trick is that the isdigit function does not take an argument of type char. Quoting the standard (N1570 7.4p1:

    The header declares several functions useful for classifying and mapping characters. In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF. If the argument has any other value, the behavior is undefined.

    The type char may be either signed or unsigned. If it's signed (as it very commonly is), then it can hold negative values -- and passing a negative value other than EOF (typically -1) to isdigit, or to any of the other functions declared in , causes undefined behavior.

    The solution is to convert the argument to unsigned char before passing it to isdigit:

    char c = -46;
    if (isdigit((unsigned char)c) {
        puts("It's a digit (?)");
    }
    else {
        puts("It's not a digit");
    }
    

    And yes, this is exactly as annoying and counterintuitive as you think it is.

提交回复
热议问题