Keyboard input/Flush the keyboard buffer: Difference between revisions

Line 808:
=={{header|C}}==
===Simple solution for stdin===
<lang|c>#include <stdio.h>
#include <stdlib.h>
 
 
int main(int argc, char* argv[])
{
// Get a chance to make stdin input buffer dirty.
//
char text[256];
getchar();
 
 
// This DOES NOT WORK properly on all modern systems including Linux & W10.
// Obsolete, don't use this. BTW, there is no fpurge in MSVC libs in 2020.
//
fflush(stdin);
 
// Always works. The only difference is (?) that readed characters may
// remain somethere in RAM.
//
fseek(stdin, 0, SEEK_END);
 
// BTW, a very dirty solution is below - an unbuffered stream does not need
// any flushing etc. It should be safe - i.e. if called before any I/O then
// no trace of buffered characters remain in RAM. Use with care.
//
setvbuf(stdin, NULL, _IONBF, 0);
 
 
// Now we are able to check if the buffer is really empty.
// BTW, NEVER use gets due to possible the buffer overrun.
//
fgets(text, sizeof(text), stdin);
puts(text);
 
return EXIT_SUCCESS;
}</lang>
 
===POSIX===
{{libheader|POSIX}}