I want to know how to clear the input buffer? Someone tell me the steps for doing the same also enrich my knowledge by putting your ideas on is it necessary that we do it while coding C program
I want to know how to clear the input buffer? Someone tell me the steps for doing the same also enrich my knowledge by putting your ideas on is it necessary that we do it while coding C program
This can be done by using the flush in C programming language.Sometimes it is necessary to forcefully flush a buffer to its stream. In that case this function flush can be used. The general syntax of this function is
int fflush(FILE *stream);
fflush(stdin) function can be used to clear the input buffer.
Without using fflush we can clear the buffer using the code:
int main(void)
{
int ch;
char buf[BUFSIZ];
puts("Flushing input");
while ((ch = getchar()) != '\n' && ch != EOF);
printf ("Enter some text: ");
if (fgets(buf, sizeof(buf), stdin))
{
printf ("You entered: %s", buf);
}
return 0;
}
Contrary to the answers you've gotten so far, you do not want to use fflush to clear an input stream. From the C Language Standard:
Emphasis mine. Calling fflush on an input stream may clear the stream, or it may not; it may leave the stream in a bad state. Since the behavior is left undefined, the implementation is free to handle the situation any way it wants to. Short answer is, don't use fflush to clear an input stream. Better to read from the stream until you see a newline or EOF character.7.19.5.2 The fflush function
...
2 If stream points to an output stream or an update stream in which the most recent
operation was not input, the fflush 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.