区分C中的字母和整数 [英] Distinguish between a letter and integer in C
本文介绍了区分C中的字母和整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请注意,我并不是想像 ctype.h 中的 isalpha() 等函数那样区分单个数字和字母(或其他字符)
Please note that I'm NOT trying to distinguish between a single digit and a letter (or other character) as done by functions like isalpha() in ctype.h
我试图区分整数和字母.
I'm trying to distinguish between an integer and an alphabet.
问题是字母在 C 中也被视为整数,我想不出办法.
The problem is that an alphabet is also treated as an integer in C and I can't think of a way out.
例如:如果输入是字母a,它与'a'相同,即整数97.
eg: if input is the letter a, it is the same as 'a' which is the integer 97.
我需要确定输入是 'a' 还是 97.
And I need to find if 'a' or 97 was the input.
我尝试这样做并意识到它根本行不通.
I tried to do this and realised it simply couldn't work.
int a;
scanf("%d", &a);
if( (a>='A' && a<='Z') || (a>='a' && a<='z') )
{
printf("
Alphabet");
}
推荐答案
查看scanf()的返回值
int val;
int chk = sscanf("a", "%d", &val);
if (chk == 1) /* all ok */;
if (chk == 0) /* no assignments */;
if (chk == EOF) /* error */;
或
int val;
int chk = sscanf("97", "%d", &val);
if (chk == 1) /* all ok */;
if (chk == 0) /* no assignments */;
if (chk == EOF) /* error */;
或
int val1, val2, val3;
int chk = sscanf("97 b 99", "%d%d%d", &val1, &val2, &val3);
if (chk == 3) /* all ok */;
if (chk == 2) /* only val1 and val2 were assigned a value */;
if (chk == 1) /* only val1 was assigned a value */;
if (chk == 0) /* no assignments */;
if (chk == EOF) /* error */;
这篇关于区分C中的字母和整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文