【问题标题】:After the first loop run, i get stuck at the default case inside the switch第一次循环运行后,我卡在开关内的默认情况下
【发布时间】:2017-03-30 03:35:46
【问题描述】:

1.由于某种原因,我在第一次循环运行后卡在默认情况下,无论我输入什么“y”或“n”。

    while(edit==1){

        option='\0';
        printf("Would you like to edit?(y or n)\n");
        scanf("%c",&option);
        getchar();

          // getchar() so if forces scanf()

        switch(option){

            // first run is flawless

            case 'y':
                printf("What would like to edit?\n");
                printf("1)Edit an entire line.\n");
                printf("2)Edit a substring of a line.\n");

                scanf("%c",&option);

                if(option=='1'){

                } else if(option =='2'){

                    printf("What word to change :");
                    scanf("%s",toFind);

                    printf("What would to change \"%s\" to :", toFind);
                    scanf("%s",replaceWith);

                    printf("which line to search :");
                    scanf("%d",&line);

                    replaceInString(buffer[line], toFind, replaceWith);
                    printBuffer(buffer);

                } else printf("Invalid input!!!\nTry again\n");
                edit=1;
                break;

            case 'n':
                edit=0;
                printBuffer(buffer);
                break;

            default:
                printf("Invalid input!!!\nTry again\n");
                // first run is fine then i get stuck here.
        }
    }

【问题讨论】:

  • 如果您到达此页面,我的解决方法是将第一个 scanf 从 scanf("%c",&option) 更改为 scanf(" %c",&option)。我在`%c`前加了一个空格

标签: c while-loop switch-statement


【解决方案1】:

当您使用 scanf 读取字符时 - 您将输入 y 并按 。 y 将分配给选项(即选项 - Y)并将在缓冲区中。当您下次调用 scanf 时,缓冲区中的存在将被分配给选项,因此进入默认情况。 为避免这种情况,请在 scanf 中的 %c 之前留一个空格。这在整数或浮点数的情况下不会发生。

【讨论】:

    猜你喜欢
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 2013-06-25
    • 1970-01-01
    相关资源
    最近更新 更多