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 the carriage return. However if if use __fpurge(stdin);
between each scanf the code works as expected. But if I use read(STDIN_FILENO,&a,1);
instead of scanf, it does not work. For read()
, only tcflush(STDIN_FILENO,TCIOFLUSH);
works but it fails with scanf. Can someone explain me why?
fpurge
empties the buffer at C level, which is the level at which scanf
works.
tcflush
does it at a lower level (system level), which is the level at which read
works.
scanf
uses read
to fill its own buffer.
So in the first case: emptying the C-buffer with scanf
works well, but does nothing at the system-level.
In the second case, emptying the system-buffer of course works with read
but not with scanf
because when you use scanf
, data up at least up to the carriage return are already present in the C-buffer. The first scanf
, reads plenty of data, place them into a buffer and then use that buffer to return you only one char. Then you tcflush
which flushes the system-level buffer but does nothing to the C-buffer, so the following scanf
is able to find the carriage return in it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.