簡體   English   中英

帶有嵌套 scanf 的 C 中的 while 循環

[英]while loop in C with nested scanf

以下代碼有什么問題? 為什么我輸入c后,程序會輸出“請選擇命令:”兩次? 以及為什么如果我先輸入i,然后輸入e,程序不會輸出“你選擇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 (換行符),您需要清除它,這樣您的循環就不會在沒有輸入的情況下再次運行。

只需放一個空格

scanf(" %c",&command);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM