我想要一个菜单,您可以从中选择一些操作。
问题是,当我们选择一个并按下“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/