C - 跳过用户输入?

lap*_*pin 4 c printf flush switch-statement

我想要一个菜单​​,你可以从中选择一些动作.

问题是,当我们选择一个,并按下"返回"键时,将跳过应该是下一步的用户输入命令.这是为什么 ?

代码是:

#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);
}
Run Code Online (Sandbox Code Playgroud)

P.P*_*.P. 5

scanf()留下后续调用所消耗的换行符gets().

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

int c;
while((c= getchar()) != '\n' && c != EOF); 
Run Code Online (Sandbox Code Playgroud)

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

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

int do_this();
Run Code Online (Sandbox Code Playgroud)

在源文件的顶部.