c - while 在 C 中使用嵌套 scanf 循环

标签 c while-loop 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(换行符),您需要清除它,这样您的循环就不会在没有输入的情况下再次运行。

关于c - while 在 C 中使用嵌套 scanf 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32130197/

相关文章:

c - 无限循环 scanf 函数

创建 scanf 以格式化文本文件

c - 如何在机器级别或内存级别的编译器中实现变量的范围

c - 在鼠标事件后重新启动无限循环?

mysql - Wordpress MySQL 结果资源无效

python - 如何在 Python 代码中使用字符和嵌套 while 循环绘制倒三角形?

c - scanf() 格式字符串中尾随空格的影响是什么?

c - 如何清除 C 中的输入缓冲区?

c - pthread_join 中的段错误

c - main() 递归调用 main() - gdb 回溯不显示多个 main() 帧 - 为什么?