【问题标题】:how to validate both lowercase and uppercase letters如何验证小写和大写字母
【发布时间】:2016-05-29 02:07:48
【问题描述】:

下面我编写了一个程序来评估字母等级并根据分数的好坏打印一条消息。假设我想从用户输入中获取该信息,我如何能够同时接受小写和大写字母?

 #include <stdio.h>
 int main (){
     /* local variable definition */
     char grade = 'B';

     if (grade == 'A'){ 
         printf("Excellent!\n");
     }
     else if (grade == 'B' || grade == 'C'){
         printf("Well done\n");
     }
     else if (grade == 'D'){
         printf("You passed\n" );
     }
     else if (grade == 'F'){
         printf("Better try again\n" );
     }
     else {
         printf("Invalid grade\n" );
     }
     printf("Your grade is %c\n", grade );
     return 0;
 }

【问题讨论】:

    标签: c++ if-statement


    【解决方案1】:

    我怎样才能同时接受小写和大写字母?

    您想在执行检查之前使用toupper() 规范化grade


    您也可以使用switch() 声明,例如

     switch(toupper(grade)) {
     case 'A':
          // ...
         break;
     case 'B':
     case 'C': // Match both 'B' and 'C'
          // ...
         break;
     }
    

    更难的方法是检查小写:

     if (grade == 'A' || grade == 'a'){ 
        // ...
     }
     else if (grade == 'B' || grade == 'b' || grade == 'C' || grade == 'c'){
        // ...
     }
     // ...
    

    【讨论】:

    • 请注意,等级应该(转换为?)一个无符号字符以便将其传递给 toupper,因为 toupper 期望输入是 EOF 或无符号字符值;任何其他负值都会导致 UB!
    【解决方案2】:

    您可以接受用户的输入并将其设为大写字母,因此如果他们输入小写或大写字母,您将始终将其视为大写字母。

    char input;
    std::cin >> input;
    input = toupper(input);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多