Drew
Drew

Reputation: 73

how to validate both lowercase and uppercase letters

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

Upvotes: 5

Views: 9313

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

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'){
    // ...
 }
 // ...

Upvotes: 6

sebenalern
sebenalern

Reputation: 2561

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);

Upvotes: 1

Related Questions