问题
My program compiles ok but it when it calls the getinput() function it never prompts for input.
Edited to show more code, I added fflush but it still skips it for some reason.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main(){
char mystring[] = "It's equal to it. ";
int k = 32;
int e;
printf("Enter a number: ");
scanf("%d",&e);
if(e == k){
printf("\n\n%s\n",mystring);
} else if(e < k){
printf("\n\n%d\n",e);
} else {
getinput();
}
exit(0);
}
int getinput(){
char gettext[64];
printf("Enter text here: ");
fflush(stdout);
fgets(gettext, 64, stdin);
printf("\n\nYou entered: %s\n\n",gettext);
return 0;
}
回答1:
after this line scanf("%d",&e)
add a getchar()
like this :
scanf("%d",&e);
getchar();
when you press Enter
the newline character stays in the buffer so when fgets
is called the newline is passed to it and it actes as if you pressed Enter
回答2:
Try calling fflush(stdout);
after your first printf.
printf
will flush it for you, but only when it has a newline at the end (e.g. printf("hi\n");
)
来源:https://stackoverflow.com/questions/20150845/c-program-skips-fgets