QQ said:
for instance, I read a char from the input
and I need to decide whether it is a letter or a number
What I am doing is
char a;
...... // read a
int true = false;
That's terribly confusing. You have defined false previously, hopefully
as 0, and are now defining a new variable 'true' and giving it the value
of 'false'!
It's poor style to define your own variables with names 'true' and
'false'. They are defined by the said:
if(( (a >='0') && (a <='9')) | | ((a >='a') && (a <= 'z')) ||((a >='A')
&& (a <= 'Z')))
true = 1;
Because digits are guaranteed to be consecutive and in order from 0 to
9, you can determine digit by (a >= '0') && (a <= '9').
However, letters are not guaranteed to be consecutive and in order. You
should never check for letters by (a >= 'a') && (a <= 'z').
Is there any easier way for it?
Absolutely!
#include <ctype.h>
char a;
// read a
if(isdigit((unsigned char)a))
{
printf("it's a number\n");
}
else if(isalpha((unsigned char)a))
{
printf("it's a letter\n");
}
else
{
printf("it's neither a number nor a letter\n");
}
Alternatively, if want a boolean value that expresses whether it's
either a number or a letter:
bool number_or_letter = isdigit((unsigned char)a)
|| isalpha((unsigned char)a);
It's important to include the cast to (unsigned char), since the is*
functions expect a non-negative argument in the range 0 .. UCHAR_MAX, or
else EOF.