代码在 '0' 情况下失败 - 我不明白为什么

标签 c while-loop switch-statement

这是强调我遇到的问题的最小形式的代码。 代码在“退出”时失败(案例“0”)——程序简单地崩溃了。我怀疑它与 while 循环有关。 无论我为退出案例选择什么字符(而不是“0”),都会出现此问题。

#include <stdio.h>

void main()
{
    int run=1;
    char menu_option; 

    while (run==1) 
    {
        printf("Choose case:\n");
        scanf ("%s", &menu_option);
        switch (menu_option) {
        case '1':
        printf("1");
        break;

        case '2':
        printf("2");
        break;

        case '0':
        run=0;
        break;

        default:
        printf("Wrong input, try again\n");

        }
    }
}

最佳答案

menu_option 不是字符串,因此 %s 是错误的格式说明符。您需要 %c,以空格为前缀以防止将空格(包括换行符)解释为有效字符输入。

    scanf (" %c", &menu_option);

关于代码在 '0' 情况下失败 - 我不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50202868/

相关文章:

c - 查找 int 数组中第一次出现的位置

c - 使用 libxml 获取节点的所有属性列表

python - 从 Erlang 运行 python 程序

java - 单击 JFrame.EXIT_ON_CLOSE 时终止 while 循环

c - 使默认语句不退出(C)

java - 如何在另一种方法中使用 findViewById 变量。 Java 安卓

c++ - 是否有最小堆大小

c++ - C/C++ : Is this undefined behavior?(二维数组)

linux - 逐行读入文件并在另一个文件中搜索部分匹配的行

c++ - 只返回第一个 if 语句? (C++)