为什么简单开关盒不起作用?

Ars*_*rsh 0 c

我希望它为每种情况分配一个字符串值,并且还能够打印

int main()
{
    int a;
    char d;
    printf("Input a Number\n");
    scanf("%d",&a);

    switch(a)
    {
    case 1:
        d='One';
    case 2:
        d='Two';
    case 3:
        d='Three';
    }

    printf("You entered %s",d);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我期望输出:

input a number
1

you entered one
Run Code Online (Sandbox Code Playgroud)

Jab*_*cky 5

您的代码有几个问题:

  1. 失踪 #include <stdio.h>
  2. 将''之间的“字符串”分配给字符
  3. 遗漏的break陈述。没有break流程的继续,程序会继续进行下去case
  4. 并不是很错误,但是风格很差:您应该使用有意义的名称来命名变量。

更正的代码:

#include <stdio.h>

int main()
{
    int number;
    const char *numbername;  // const is not mandatory
    printf("Input a Number\n");
    scanf("%d", &number);

    switch (number)
    {
    case 1:
        numbername = "One";
        break;
    case 2:
        numbername = "Two";
        break;
    case 3:
        numbername = "Three";
        break;
    }

    printf("You entered %s", numbername);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,C语言中没有“字符串”类型。请阅读初学者的C课本中有关字符串的章节。

const暂时忘记关键字,这是一个更高级的主题。