C - 用户输入被跳过?

标签 c switch-statement printf flush

我想要一个菜单​​,您可以从中选择一些操作。

问题是,当我们选择一个并按下“return”键时,本应是下一步的用户输入命令被跳过了。这是为什么?

代码是:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    int choice;

    do
    {
     printf("Menu\n\n");
     printf("1. Do this\n");
     printf("2. Do that\n");
     printf("3. Leave\n");
     scanf("%d",&choice);

     switch (choice)
     {
        case 1:
            do_this();
            break;
        case 2:
            // do_that();
            break;
     }

    } while (choice != 3);

    return(0);
}

int do_this()
{
    char name[31];

    printf("Please enter a name (within 30 char) : \n");
    gets(name); // I know using gets is bad but I'm just using it

    // fgets(name,31,stdin); // gives the same problem by the way.

    // Problem is : user input gets skiped to the next statement :
    printf("Something else \n");

    return(0);
}

最佳答案

scanf() 留下一个换行符,由随后调用 gets() 使用。

scanf() 之后立即使用 getchar(); 或使用循环读取和丢弃字符:

int c;
while((c= getchar()) != '\n' && c != EOF); 

我知道您曾评论过 gets() 不好。但是即使它是一个玩具程序,您也不应该尝试使用它。它已从最新的 C 标准 (C11) 中完全删除,即使您正在为 C89 编程(由于其缓冲区溢出漏洞)也不应该使用它。使用 fgets() 除了可能留下尾随的换行符外,它的作用几乎相同。

如果这是您的完整代码,那么您还需要一个原型(prototype)或至少一个 do_this() 的声明。隐式 int 规则也已从 C 标准中删除。所以添加,

int do_this();

在源文件的顶部。

关于C - 用户输入被跳过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34901134/

相关文章:

c - STM32F4 HAL I2C只发送地址

objective-c - PQgetResult 总是返回 NULL

c - 我可以通过哪些方式(使用 stdio)打印垂直直方图

c - fprintf() 问题 utf-8 linux

c - 重复任务/代码块 X 次(由用户引入)

c - 使用未声明的标识符 'true'

mysql - switch 语句内的奇怪结果

java - Java 中的 switch case 逻辑表达式语句 - 与 JS 或 PHP

c - 需要帮助 C 中的 Switch 语句

c - 如何将格式化数据存储到 C 中的数组?