fflush() is not working in Linux
Don't use fflush, use this function instead:
#include <stdio.h>
void clean_stdin(void)
{
int c;
do {
c = getchar();
} while (c != '\n' && c != EOF);
}
fflush(stdin)
depends of the implementation, but this function always works. In C, it is considered bad practice to use fflush(stdin)
.
The behavior of fflush
is not defined for input streams (online 2011 standard):
7.21.5.2 Thefflush
function
Synopsis
1Description#include <stdio.h> int fflush(FILE *stream);
2 If stream points to an output stream or an update stream in which the most recent operation was not input, thefflush
function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
3 Ifstream
is a null pointer, thefflush
function performs this flushing action on all streams for which the behavior is defined above.
Returns
4 Thefflush
function sets the error indicator for the stream and returns EOF if a write error occurs, otherwise it returns zero.
I faced the same problem while working on LINUX and an alternative solution of this problem can be that you define a dummy character lets say char dummy;
and put a scanf()
to scan it just before your actual input takes place. This worked for me. I hope it would work for you too.
One that always works on Linux:
#include <termios.h>
#include <unistd.h>
void clean_stdin()
{
int stdin_copy = dup(STDIN_FILENO);
/* remove garbage from stdin */
tcdrain(stdin_copy);
tcflush(stdin_copy, TCIFLUSH);
close(stdin_copy);
}
You can use tcdrain and tcflush not only for in/out/err fd.