[英]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.