iyy0v
iyy0v

Reputation: 61

Multiple chars in SWITCH CASE in C

I have a school project and I'm working on a menu where the users chooses what he wants to do. I want the choice variable to be a char, not an int. Can I add multiple chars in a single switch case? I searched for a solution but I only found one when the value is an int, not a char. I tried this but it didn't work:

char choice;
scanf("%c", &choice); 
switch(choice)
{
case 'S', 's':
    // do something
    break;
case 'I', 'i':
    // do another thing
    break;
default:
    printf("\nUnknown choice!");
    break;
}

Upvotes: 3

Views: 5041

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

For starters use the following format in scanf

char choice;
scanf( " %c", &choice ); 
       ^^^

(see the blank before the conversion specifier). Otherwise the function will also read white space characters.

You can use several adjacent case labels like for example

switch(choice) 
{
    case 'S':
    case 's': 
        //do something
        break;

    case 'I':
    case 'i': 
        //do anotherthing
        break;

    default: 
        printf("\n Unknown choice !");
        break;
}

An alternative approach is to convert the entered character to the upper case before the switch. For example

#include <ctype.h>

//...

char choice;
scanf( " %c",&choice ); 

switch( toupper( ( unsigned char )choice ) ) 
{
    case 'S':
        //do something
        break;

    case 'I':
        //do anotherthing
        break;

    default: 
        printf("\n Unknown choice !");
        break;
}

Upvotes: 6

Eraklon
Eraklon

Reputation: 4288

You can use fall through like this:

case 'S':
case 's':
    // do something
    break;
case ...

Upvotes: 6

dbush
dbush

Reputation: 223972

You can put multiple case labels after each other:

switch(choice) {
case 'S':
case 's':
    //do something
    break;
case 'I':
case 'i': 
    //do anotherthing
    break;
default: 
    printf("\n Unknown choice !");
    break;
}

Upvotes: 2

Related Questions