【问题标题】:Getting "Segmentation fault (core dumped)" after prompting user for input提示用户输入后出现“分段错误(核心转储)”
【发布时间】:2018-12-27 20:17:06
【问题描述】:

无论哪种情况,Switch 语句都会导致“Segmentation fault (core dumped)”。

我尝试更改“命令”的数据类型,但无法得到任何其他结果。

    char command;
    int temp;

    while(1) {
            printf("Enter command ('d'/'m'/'s'/'r'): ");
            scanf("%c", command);
            printf("\n");

            switch(command) {
                    case 'd' :
                            printf("display which employee (0-19)?\n");
                            scanf("%i", temp);
                            //display(temp);
                            printf("displayed");
                            break;
                    case 'm' :
                            printf("modify which employee (0-19)?\n");
                            scanf("%i", temp);
                            //modify(temp);
                            printf("modified");
                            break;
                    case 's' :
                            //save();
                            printf("saved");
                            break;
                    case 'r' :
                            //retrieve();
                            printf("retrieved");
                            break;
                    default :
                            printf("Command not recognized\n");
            }
    }

预计根据相关案例打印动作。相反,它只是打印“分段错误(核心转储)”消息。

【问题讨论】:

  • scanf("%i", temp); --> scanf("%i", &temp); 由于temp 是一个int 变量,您需要提供& 以将用户输入存储到其中。还要仔细阅读编译器警告并解决它们,不要忽略它们。

标签: c


【解决方案1】:

%c 格式说明符期望 char 的地址,即 char * 被传入。您正在传入 char%iint 也同样如此。使用错误的格式说明符会调用undefined behaivor,在这种情况下表现为崩溃。

您需要传递相关变量的地址,以便scanf 可以修改它们。此外,对于%c,您应该在格式字符串之前有一个空格,以消耗输入缓冲区中剩余的任何空格。

所以你想要:

scanf(" %c", &command);

还有:

scanf("%i", &temp);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多