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
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.
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).