【问题标题】:while loop in C with nested scanf带有嵌套scanf的C中的while循环
【发布时间】:2015-08-20 23:42:56
【问题描述】:

以下代码有什么问题?为什么我输入c后,程序会输出两次“请选择命令:”?还有为什么我先输入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;
}

【问题讨论】:

    标签: c while-loop scanf


    【解决方案1】:

    试试这个

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

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

    【讨论】:

    • 谢谢!但是为什么在这种情况下在 %c 之前添加一个空格会起作用?
    • @jitron 它可以工作,因为当您在界面中输入命令时,您只是输入e,但实际上您输入的是e\n,因为您需要点击输入它以注册命令。因此,您需要在scanf 中的%c 之前添加一个空格,以清除上一条命令中的\n
    【解决方案2】:

    放一个空格

    scanf(" %c",&command);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 2020-12-30
      • 2016-05-03
      • 2021-07-31
      • 2012-03-12
      相关资源
      最近更新 更多