问题
I want a menu from which you choose some action.
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 ?
The code is :
#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);
}
回答1:
scanf()
leaves a newline which is consumed by the subsequent call to gets()
.
Use getchar();
right after scanf()
or use a loop to read and discard chars:
int c;
while((c= getchar()) != '\n' && c != EOF);
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.
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();
at the top of your source file.
回答2:
scanf("%d",&choice);
This leaves the newline ('\n'
) in the standard input buffer stdin
.
Your call of gets()
merely consumes that whitespace, writing nothing into name
.
To prevent this, consume the newline char after you call scanf, for instance by using getchar()
. If you are not on a microsoft platform, please do not use fflush(stdin)
, as that is undefined behavior (on non-MS platforms).
来源:https://stackoverflow.com/questions/34901134/c-user-input-getting-skipped