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?
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;
}
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!!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With