I have test code like this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char c, str[20];
printf("Enter a character : ");
scanf("%c", &c);
printf("Enter a string : ");
fflush(stdin);
gets(str);
printf("\n\n\nResult : %c\n%s\n", c, str);
return 0;
}
I read in some articles that this code will work, because after scanning the character c in the buffer there is still the character "\ n". Fflush (stdin) will clear the buffer, so the gets () function may work fine
But actually, when I compile and run this code on a Mac OS environment, fflush (stdin) does nothing. I entered a character (for example, "k"), then it will print the character k and the character "\ n". It allows me to enter a character, a string, and then print both of them. Does anyone know why? Thank!
source
share