while 在 C 中使用嵌套 scanf 循环

while loop in C with nested scanf

以下代码有什么问题?为什么我输入c后程序会输出两次"please choose the command: "?还有为什么我先输入i,再输入e,程序不会输出"you choose e"

#include <stdio.h>

void interface(){
char command;
printf("please choose the command: \n");
scanf("%c",&command);
if (command == 'c'){
    printf("you choose c\n");
}
else if (command == 'i'){
        printf("you choose i, what is next?: \n");
        scanf("%c",&command);
        if (command == 'e'){
            printf("you choose e\n");
        }
}
else if (command == 'p'){
        printf("you choose p, what is next?: \n");
        scanf("%c",&command);
        if (command == 'a'){
            printf("you choose a\n");
        }
}
}



int main(int argc, char const *argv[])
{
    while(1){
        interface();
    }
    return 0;
}

试试这个

...
scanf(" %c", &command);
...

问题是您的输入缓冲区中有一个 \n(换行符),您需要清除它,这样您的循环就不会在没有输入的情况下再次 运行。

就放一个白色的space

scanf(" %c",&command);