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
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 anunsigned char
or shall equal the value of the macroEOF
. 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.