下面的代码有什么问题?为什么我输入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
(换行符),您需要清除它,这样您的循环就不会在没有输入的情况下再次运行。
关于c - while 在 C 中使用嵌套 scanf 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32130197/