【问题标题】:How to check if a string is a letter(a-z or A-Z) in c如何检查字符串是否是c中的字母(a-z或A-Z)
【发布时间】: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) == 1 for sscanf(..., "%d",...) 可能会返回0、1 或EOF。

标签: c char uppercase lowercase ctype


【解决方案1】:

您可以使用isalpha()isdigit() 标准函数。只需包含<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 
     }

【讨论】:

  • 感谢您的建议,但是如何将缓冲区更改为整数?
  • 只使用缓冲区的第一个字符并将其转换为int
【解决方案2】:

判断输入是字母还是数字

  • int isalpha ( int c ); 函数验证c 是否为字母
  • int isalnum ( int c ); 函数验证c十进制数字还是大写或小写字母
  • int isdigit ( int c ); 函数验证c 是否为十进制数字字符

判断字母是大写还是小写

  • int islower ( int c ); 检查c 是否为小写字母a-z
  • int isupper ( int c ); 检查c 是否为大写字母A-Z

根据结果将它们放入if 执行某些操作的语句(truefalse)中。

PS你可以在这里找到更多关于标准库的信息:Character handling functions: ctype.h

【讨论】:

    猜你喜欢
    • 2018-03-16
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多