问题描述
我想要一个菜单,您可以从中选择一些操作.
I want a menu from which you choose some action.
问题是当我们选择一个并按下return"键时,应该是下一步的用户输入命令被跳过了.这是为什么呢?
Problem is that when we choose one, and press the "return" key, the user input command which should have been the next step, is skipped. Why is that ?
代码是:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int choice;
do
{
printf("Menu
");
printf("1. Do this
");
printf("2. Do that
");
printf("3. Leave
");
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) :
");
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
");
return(0);
}
推荐答案
scanf()
留下一个换行符,供后续调用 gets()
使用.
scanf()
leaves a newline which is consumed by the subsequent call to gets()
.
在 scanf()
之后使用 getchar();
或使用循环读取和丢弃字符:
Use getchar();
right after scanf()
or use a loop to read and discard chars:
int c;
while((c= getchar()) != '
' && c != EOF);
我知道你评论说 gets()
不好.但即使它是一个玩具程序,你也不应该尝试使用它.它已完全从最新的 C 标准 (C11) 中删除,即使您正在为 C89 编程(由于其缓冲区溢出漏洞)也不应该使用它.使用 fgets()
,它的作用几乎相同,但可能会留下一个尾随换行符.
I know you have commented about gets()
being bad. But you shouldn't even attempt to use it even if it's a toy program. It's been removed from the latest C standard (C11) completely and shouldn't be used even if you are programming for C89 (due to its buffer overflow vulnerabilities). Use fgets()
which does almost the same except possibly leaves a trailing newline.
如果这是您的完整代码,那么您还需要一个原型或至少一个 do_this()
的声明.隐式 int 规则也已从 C 标准中删除.所以添加,
If this is your complete code, then you would also need a prototype or at least a declaration for do_this()
. Implicit int rule has also been removed from C standard. So add,
int do_this();
在源文件的顶部.
这篇关于C - 用户输入被跳过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!