如何在c中检查字符串是否为字母(a-z或A-Z) [英] How to check if a string is a letter(a-z or A-Z) in c
本文介绍了如何在c中检查字符串是否为字母(a-z或A-Z)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在获得用户输入,我想确定用户是否输入了字母,整数或运算符。我可以使用sscanf成功地确定它是否是整数,但是我对如何确定它是否是一个字母感到困惑。
I am getting user input, and I want to determine if the user has entered a letter , an integer, or an operator. I can successfully determine if it is an integer using sscanf, but I am stumped on how to determine if it is a letter.
按字母表示,我的意思是:AZ,az 。
By letter, I mean: A-Z, a-z.
int main(){
char buffer[20];
int integer;
printf("Enter expression: ");
while (fgets(buffer, sizeof(buffer), stdin) != NULL){
char *p = strchr(buffer, '\n'); //take care of the new line from fgets
if (p) *p = 0;
//Buffer will either be a integer, an operator, or a variable (letter).
//I would like a way to check if it is a letter
//I am aware of isalpha() but that requires a char and buffer is a string
//Here is how I am checking if it is an integer
if (sscanf(buffer, "%d", &integer) != 0){
printf("Got an integer\n");
}
else if (check if letter)
// need help figuring this out
}
else{
// must be an operator
}
}
}
推荐答案
您可以使用 isalpha()
和 isdigit()
标准函数。只需包含< ctype.h>
。
You can use the isalpha()
and isdigit()
standard functions. Just include <ctype.h>
.
if (isdigit(integer)) != 0){
printf("Got an integer\n");
}
else if (isalpha(integer))
printf"Got a char\n");
}
else{
// must be an operator
}
这篇关于如何在c中检查字符串是否为字母(a-z或A-Z)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文