如何验证小写和大写字母

时间:2016-05-29 02:07:49

标签: c++ if-statement

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

 #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;
 }

2 个答案:

答案 0 :(得分:6)

  

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

您希望在执行检查之前使用toupper()grade进行规范化。

您还可以使用{/ 1}}语句,例如

switch()

更难的方法是检查小写:

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

答案 1 :(得分:1)

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

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