Why does tcflush not work for scanf?

I have this simple code to accept 3 characters:

char a,b,c;
scanf("%c",&a);
scanf("%c",&b);
scanf("%c",&c);
printf("%c",a);
printf("%c",b);
printf("%c",c);

I understand why this will only accept 2 characters, because the second scanf accepts a carriage return. However, if, when used __fpurge(stdin);between each scanf, the code works as expected. But if I use read(STDIN_FILENO,&a,1);scanf instead, this will not work. For read()only works tcflush(STDIN_FILENO,TCIOFLUSH);, but it does not work with scanf. Can someone explain to me why?

+4
source share
1 answer

fpurgeempties the buffer at level C, which is the level at which it runs scanf.

tcflush ( ), , read.

scanf read .

, : C- scanf , .

, , read, scanf, , scanf, , , , C- . scanf, , , , char. tcflush, , C-, scanf .

+6

All Articles