C - 用户输入被跳过?

C - User input getting skipped?

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

问题是,当我们选择一个并按下 "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() 除了可能留下一个尾随换行符外,它的作用几乎相同。

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

int do_this();

在源文件的顶部。

scanf("%d",&choice);

这会在标准输入缓冲区 stdin.

中留下换行符 ('\n')

您对 gets() 的调用仅消耗了该空白,未向 name.

写入任何内容

为防止这种情况,请在调用 scanf 后使用换行符,例如使用 getchar()。如果您不在 Microsoft 平台上,请不要使用 fflush(stdin),因为这是未定义的行为(在 non-MS 平台上)。