Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
 }
like image 903
Drew Avatar asked May 29 '16 02:05

Drew


1 Answers

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'){
    // ...
 }
 // ...
like image 144
πάντα ῥεῖ Avatar answered Nov 14 '22 23:11

πάντα ῥεῖ