【问题标题】:ask user for input in a swich statement that will generate another swich in c询问用户在 switch 语句中的输入,该语句将在 c 中生成另一个 switch
【发布时间】:2017-03-12 16:23:21
【问题描述】:

如何在 switch 语句中要求用户输入将在 c 中生成另一个 switch,我尝试了这个但我的程序崩溃了。

#include <stdio.h>
#include <stdlib.h>

int main()
{

    char choise1, choise2;

    printf("Starting menu:\n a -> Start\n");
    choise1 = getchar();

    switch(choise1){

    case 'a':
        printf("\n a -> New Game\n b -> Load Game");
        choise2 = getchar();
        switch(choise2){
        case 'a':
            printf("Start new game.");
            break;
        case 'b':
            printf("Loading game.");
            break;
        default:
            printf("This is a wrong input.");
        }
        break;

    default:
        printf("This is a wrong input.");

    }

    return 0;
}

【问题讨论】:

标签: c newline getchar


【解决方案1】:

我看到这里的问题是由于输入缓冲区的剩余输入。

当你输入 a 并按下 ENTER 时,输入缓冲区中的a 后面会存储一个newline,它将在下次调用时返回getchar().

如果您希望连续调用getchar() 以返回有效 输入,则需要先清除现有内容的输入缓冲区,然后才能读取下一个输入。查看this answer 了解一些解释清楚的方法。

也就是说,

  • getchar() 返回 int,对于某些返回值,例如 EOF,它可能不适合 char。将choise1choise2 类型更改为int
  • int main() 至少应该是 int main(void),以使托管环境符合标准。

【讨论】:

  • 看看this answer 这样做。
  • @cbuchart 是的,不错的主播。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 2018-09-30
  • 2014-02-06
  • 1970-01-01
相关资源
最近更新 更多