How can I validate a each character of an array to check if it is numeric? ie
if (num[1] != 0)
......
but I want to check against all digits, 0-9 using one line of code? I know there is a way like, [0-9], but cannot find it?
How can I validate a each character of an array to check if it is numeric? ie
if (num[1] != 0)
......
but I want to check against all digits, 0-9 using one line of code? I know there is a way like, [0-9], but cannot find it?
I don't want to use isdigit!
And why that?Originally posted by spaceboo
I don't want to use isdigit!
so build your own one, that I think this should be very close to the isdigit one.
I've done something like this before using ascii values. As '0' has as ascii value of 48, and '9' has an ascii value of 57, then...
then buf[x] is a digit.Code:n = buf[x] - 48; if( ( n < 10 ) && ( n >= 0 ))
So get your string in a buffer, set up a for loop, and for each character in the string, do the above check.
I'm sure anything you make will be very close to isdigit(). Although if you have a real need of 'one line comparison' I suppose you can create a regexp in C and compare it to that. Heh.
If I were avoiding isdigit, I would do this.How can I validate a each character of an array to check if it is numeric? ie
if (num[1] != 0)
......
but I want to check against all digits, 0-9 using one line of code? I know there is a way like, [0-9], but cannot find it?Using '0' and '9' is more portable than using their ASCII equivalents 48 and 57 because it need not be ASCII.Code:if(num[1] >= '0' && num[1] <= '9') /* ... */
One "[0-9]" method is as follows.Although the %[0-9] is a common extension, it is non-standard. A standard version would be like this.Code:char digit[2]; if(sscanf(&num[1], "%1[0-9]", digit) == 1) /* ... */It meets the "one line" criteria (if you declare digit with num), but to me it seems quite excessive.Code:if(sscanf(&num[1], "%1[0123456789]", digit) == 1) /* ... */