Sunday 20 November 2011

How do you tell whether a character is a number? in C programming

How do you tell whether a character is a number?

As shown in the ASCII chart in FAQ XX.18, character numbers are defined to be in the range of decimal 48 to 57, inclusive (refer to FAQ XX.18 for more information on the ASCII chart). Therefore, to check a character to see whether it is a number, see the following example code:

int ch;
ch = getche();
if( (ch >= 48) && (ch <= 57) )
printf(“%c is a number character between 0 and 9\n”, ch);
else
printf(“%c is not a number\n”, ch);
As in the preceding FAQ, you can check the variable against the number character range itself, as shown here:
int ch;
ch = getche();
if( (ch >= ‘0’) && (ch <= ‘9’) )
printf(“%c is a number character between 0 and 9\n”, ch);
else
printf(“%c is not a number\n”, ch);
As before, which method you choose is up to you, but the second code example is easier to understand.

Cross Reference:

XX.18: How do you tell whether a character is a letter of the alphabet?

No comments:

Post a Comment