Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make switch-case statements case insensitive?

Tags:

c

How can I make a switch-case statement to not be case sensitive? Say I made something like this:

#include <stdio.h>

char choice;
int main ()
{
char choice;
printf("Will you choose A,B, or C?\n>");
scanf(" %c", &choice);

switch(choice)
{
    case 'A': 
         printf("The First Letter of the Alphabet");
         break;
    case 'B':
         printf("The Second Letter of the Alphabet");
         break;
    case 'C':
         printf("The Third Letter of the Alphabet");
         break;
}
}

It would only respond to capital letters. How do I make it respond to lower case letters?

like image 749
Jeremy Avatar asked Oct 13 '14 15:10

Jeremy


2 Answers

toupper in <ctype.h> converts a character to uppercase:

#include <stdio.h>
#include <ctype.h>

char choice;
int main ()
{
printf("Will you choose A,B, or C?\n>");
scanf(" %c", &choice);

switch(toupper(choice))  // Changed line
{
    case 'A': 
         printf("The First Letter of the Alphabet");
         break;
    case 'B':
         printf("The Second Letter of the Alphabet");
         break;
    case 'C':
         printf("The Third Letter of the Alphabet");
         break;
}
like image 52
Klas Lindbäck Avatar answered Oct 25 '22 22:10

Klas Lindbäck


You simply need this :-

switch(choice)
{
case 'A': 
case 'a':
     printf("The First Letter of the Alphabet");
     break;
case 'B':
case 'b':
     printf("The Second Letter of the Alphabet");
     break;
case 'C':
case 'c':
     printf("The Third Letter of the Alphabet");
     break;
}

and so on to continue your series.

Actually,what it does is that it bypasses(skims) upto bottom until it finds the first break statement matching the case thereby executing all the cases encountered in between!!!

like image 42
Am_I_Helpful Avatar answered Oct 25 '22 20:10

Am_I_Helpful