Er.....i want to detect if a character is a number between 0 and 9
i achieve this using ascii rite? er......how do i specify this in the if statement?
Printable View
Er.....i want to detect if a character is a number between 0 and 9
i achieve this using ascii rite? er......how do i specify this in the if statement?
Code:#include <stdio.h>
int main() {
char test1 = 'a';
char test2 = '2';
function(&test1);
function(&test2);
return 0;
}
int function(char *test) {
if(*test < '0' || *test > '9') {
printf("not a character between 0-9\n");
return 1;
}
printf("is a character between 0-9\n");
return 0;
}
The standard library function isdigit will return true if the character is a digit.Code:#include <stdio.h>
#include <ctype.h>
int main(void)
{
char *ptr, number[] = "*_42-Aa0";
for ( ptr = number; *ptr != '\0'; ++ptr )
{
if ( isdigit(*ptr) )
{
printf("'%c' is a digit\n", *ptr);
}
else
{
printf("'%c' is not a digit\n", *ptr);
}
}
return 0;
}
/* my output
'*' is not a digit
'_' is not a digit
'4' is a digit
'2' is a digit
'-' is not a digit
'A' is not a digit
'a' is not a digit
'0' is a digit
*/
Well, since you are talking about characters, and not numbers- you could just say:Quote:
Originally posted by fkheng
Er.....i want to detect if a character is a number between 0 and 9
i achieve this using ascii rite? er......how do i specify this in the if statement?
dCode:void foo(void)
{
char myLetter;
myLetter = 'j'; /* stuff a non-digit value in */
if((myLetter <= '9') && (myLetter >= '0'))
Success();
else
Failure();
}
i see, thanx, many alternatives to the code...
about the isdigit, i recall using it, but somehow it could not detect number characters, i really do not know y...anyway, thanx ppl, the codes work!