C-开关盒两次打印盒

时间:2020-05-02 11:41:56

标签: c switch-statement scanf getchar

我写了以下开关盒:

    char input;
    int run = 1;
    while(run){
        printf("Would you like to update the student's name? Enter Y or N (Y=yes, N=no)\n");
        input = getchar();
        switch (input)
        {
        case 'N':
            run = 0;
            break;
        case 'n':
            run = 0;
            break;
        case 'Y':
            printf("Please enter the updated name\n");
            scanf("%s", st->name);
            run = 0;
            break;
        case 'y':
            printf("Please enter the updated name\n");
            scanf("%s", st->name);
            run = 0;
            break;
        case '\n':
            break;
        default:
            printf("Wrong input. Please enter a valid input (Y or N)\n");
        }
    }

当我运行它时会这样做:

Please enter the id of the student that you would like to update
1
Would you like to update the student's name? Enter Y or N (Y=yes, N=no)
Would you like to update the student's name? Enter Y or N (Y=yes, N=no)

为什么它两次打印问题?有人可以帮忙吗? 除此之外,这些案例按预期运行。

1 个答案:

答案 0 :(得分:2)

函数getchar读取所有字符,包括换行符。改为使用

scanf( " %c", &input );

您的switch语句也有重复的代码。例如写

    switch (input)
    {
    case 'N':
    case 'n':
        run = 0;
        break;
    case 'Y':
    case 'y':
        printf("Please enter the updated name\n");
        scanf("%s", st->name);
        run = 0;
        break;
   //...

您可以将相同的方法用于switch语句的其他标签。并删除此代码

    case '\n':
        break;