c - C 中 SWITCH CASE 中的多个字符

标签 c char switch-statement

我有一个学校项目,我正在制作一个菜单,用户可以在其中选择他想做的事情。我希望选择变量是 char ,不是 int .我可以在一个 switch 中添加多个字符吗?案件?我搜索了一个解决方案,但我只在值为 int 时找到了一个解决方案。 ,不是 char .我试过这个,但没有用:

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;
}

最佳答案

对于初学者在 scanf 中使用以下格式

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

(参见转换说明符前的空白)。否则,该函数还将读取空白字符。

您可以使用几个相邻的案例标签,例如
switch(choice) 
{
    case 'S':
    case 's': 
        //do something
        break;

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

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

另一种方法是在切换之前将输入的字符转换为大写。例如
#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;
}

关于c - C 中 SWITCH CASE 中的多个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60624380/

相关文章:

javascript - 如何为每个 switch 语句更改添加淡入淡出的 css 样式和图像

c - 打印c中每个子进程产生的值

c++ - cygwin1.dll 丢失 - 无法运行程序

c++ - 在 C++ 中将整数存储到 char* 中

c++ - c++ 4个字符中哪个字符排在第一个

javascript - JS : Why don't the switch statement cases `case 2` and `case day == 2` print out the same result?

CS50破解问题。需要有关如何解密 2-4 个字符的单词的帮助

c++ - 如果我们添加安全的有符号/无符号比较 C/C++,它会破坏语言或现有代码吗?

c++ - 用另一个替换多维数组?

C: 使用 getchar 和 switch case 获取主菜单的用户输入的问题