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


note newbie

i've used isdigit() function before, have issue:

i need check if (for example) char value -46 digit. isdigit() doesn`t seem recognize negative numbers (probably because of - before actual number).

is there simple line of code can have same effect isdigit() function, detects negative numbers well? (like ascii table range or something)

let me clarify myself further: have char type array: char a[20] enter each value manually (example):

a[0]= a[1]= b a[2]= -46 

now 3 (ignore remaining 17 - example), need check if of digit. -46 number i`m searching (to put in array), question how check if -46 "is digit"?

the trick isdigit function not take argument of type char. quoting standard (n1570 7.4p1:

the header <ctype.h> declares several functions useful classifying , mapping characters. in cases argument int, value of shall representable unsigned char or shall equal value of macro eof. if argument has other value, behavior undefined.

the type char may either signed or unsigned. if it's signed (as commonly is), can hold negative values -- , passing negative value other eof (typically -1) isdigit, or of other functions declared in <ctype.h>, causes undefined behavior.

the solution convert argument unsigned char before passing isdigit:

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

and yes, annoying , counterintuitive think is.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -