Why fflush (stdin) does not delete the buffer (stdin)

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!

-1
source share
2 answers

fflush (3) , .

.

POSIX fflush . , , undefined POSIX.

Linux fflush(stdin) ( ),

fflush()         ,         .

BTW, (3) , ( !) C11 . fgets (3) getline (3) . , GNU readline ( ).

+8

fflush(stdin) - undefined behavior.

fflush() streams open for output, . , , C, ! , .

+4

Source: https://habr.com/ru/post/1651150/


All Articles