【发布时间】:2013-11-22 16:21:37
【问题描述】:
我正在获取用户输入,并且我想确定用户是否输入了字母、整数或运算符。我可以使用 sscanf 成功确定它是否是一个整数,但是我很难确定它是否是一个字母。
我的意思是: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
}
}
}
【问题讨论】:
-
顺便说一句:如果您只输入空格,
(sscanf(" ", "%d", &integer)将产生 -1 并通过您的“得到一个整数\n”测试。建议将来使用肯定sscanf()比较测试,例如sscanf(buffer, "%d", &integer) == 1forsscanf(..., "%d",...)可能会返回0、1 或EOF。
标签: c char uppercase lowercase ctype