在C编程中,字符变量存储的是ASCII值(0到127之间的整数),而不是字符本身。
小写字母的ASCII值范围是97到122。大写字母的ASCII值范围是65到90。
如果用户输入的字符的ASCII值在97到122或65到90的范围内,那么它就是字母。
检查字母的程序
#include <stdio.h>
int main() {
char c;
printf("Enter a character: ");
scanf("%c", &c);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
printf("%c is an alphabet.", c);
else
printf("%c is not an alphabet.", c);
return 0;
}
输出
Enter a character: * * is not an alphabet
在程序中,我们使用'a'
而不是97
,使用'z'
而不是122
。同样,我们使用'A'
而不是65
,使用'Z'
而不是90
。
注意:建议使用isalpha()函数来检查一个字符是否是字母。
if (isalpha(c))
printf("%c is an alphabet.", c);
else
printf("%c is not an alphabet.", c);