简体   繁体   English

C 中 SWITCH CASE 中的多个字符

[英]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 .我希望选择变量是char ,而不是int Can I add multiple chars in a single switch case?我可以在一个switch case 中添加多个字符吗? I searched for a solution but I only found one when the value is an int , not a char .我搜索了一个解决方案,但我只在值为int而不是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;
}

You can use fall through like this:您可以像这样使用fall through:

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

For starters use the following format in scanf对于初学者在 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;
}

You can put multiple case labels after each other:您可以将多个case标签放在case

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM