Newline stays in buffer after fgets()?
Here is the snippet of code that is causing me problems:
#define MAX_NAME_LEN 64
char choice;
char name[MAX_NAME_LEN];
printf("Name: ");
fgets(name, MAX_NAME_LEN, stdin);
choice = getchar();
After I enter a name and press enter, getchar() captures the newline as well instead of waiting for the next character. How can I fix my code (without something hacky like another getchar() if possible) so that getchar() will wait for a character as expected after a name is enter开发者_如何学运维ed?
I am unable to replicate your problem using GCC on a Mac OS X system. Are you perhaps using a Windows system where pressing ENTER
might produce both a CR
and an LF
?
In any event, note that getchar()
will not usually return immediately after a single key press because by default on most systems stdin
is line buffered, meaning that the terminal subsystem won't deliver any characters to the user process until ENTER
is pressed.
getchar()
is not a substitute for the old DOS <conio.h>
functions like getch()
.
Getting around that depends on what O/S you're on.
精彩评论