C – 跳过用户输入?

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

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

代码是:

#include  #include  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()

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

 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() 。 如果您不在微软平台上,请不要使用fflush(stdin) ,因为这是未定义的行为(在非MS平台上)。