5

Below I have written a program to evaluate a letter grade and print a message based on how well the score is. Let's say I wanted to get that information from the user input, how would I be able to accept both lower and upper case letters?

 #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;
 }
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
Drew
  • 73
  • 2
  • 9

2 Answers2

6

how would i be able to accept both lower and upper case letters?

You want to normalize grade using toupper() before performing the checks.


You can also use a switch() statement like

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

The harder way is to check for lower case as well:

 if (grade == 'A' || grade == 'a'){ 
    // ...
 }
 else if (grade == 'B' || grade == 'b' || grade == 'C' || grade == 'c'){
    // ...
 }
 // ...
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • On a cautionary note, grade should be (converted to?) an unsigned char in order to pass it to toupper, since toupper expects the input to be EOF or an unsigned char value; any other negative values will cause UB! – autistic May 29 '16 at 04:09
1

You can take the user's input and make it a capital letter so if they enter a lowercase or uppercase letter you will always treat it as an uppercase letter.

char input;
std::cin >> input;
input = toupper(input);
sebenalern
  • 2,515
  • 3
  • 26
  • 36