简体   繁体   English

C - 开关盒打印两次

[英]C - Switch-case prints case twice

I have written the following switch-case:我写了以下开关案例:

    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");
        }
    }

When I run it does this:当我运行它时:

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)

Why does it print the question twice?为什么它会打印两次问题? Can anyone help?任何人都可以帮忙吗? Other than that the cases run as expected.除此之外,案件按预期运行。

The function getchar reads all characters including new line characters. function getchar读取所有字符,包括换行符。 Instead use而是使用

scanf( " %c", &input );

Also your switch statement has a duplicated code.您的 switch 语句也有重复的代码。 Write for example例如写

    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;
   //...

The same approach you can use for other labels of the switch statement.您可以对 switch 语句的其他标签使用相同的方法。 and remove this code并删除此代码

    case '\n':
        break;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM