fflush()

https://www.geeksforgeeks.org/use-fflushstdin-c/

fflush() is typically used for output stream only. Its purpose is to clear (or flush) the output buffer and move the buffered data to console (in case of stdout) or disk (in case of file output stream). Below is its syntax.

fflush(FILE *ostream);

ostream 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.

Can we use it for input stream like stdin?
As per C standard, it is undefined behavior to use fflush(stdin). However some compilers like Microsoft visual studio allows it allow it. How is it used in these in these compilers? While taking an input string with spaces, the buffer does not get cleared for the next input and considers the previous input for the same. To solve this problem fflush(stdin) is. used to clear the stream/buffer.

// C program to illustrate situation
// where flush(stdin) is required only
// in certain compilers.
#include <stdio.h>
#include<stdlib.h>
int main()
{
    char str[20];
    int i;
    for (i=0; i<2; i++)
    {
        scanf("%[^\n]s", str);
        printf("%s\n", str);
        // fflush(stdin);
    }
    return 0;
}

Input:

geeks   
geeksforgeeks

Output:

geeks 
geeks 

The code above takes only single input and gives the same result for the second input. Reason is because as the string is already stored in the buffer i.e. stream is not cleared yet as it was expecting string with spaces or new line. So, to handle this situation fflush(stdin) is used.

// C program to illustrate flush(stdin)
// This program works as expected only
// in certain compilers like Microsoft
// visual studio.
#include <stdio.h>
#include<stdlib.h>
int main()
{
    char str[20];
    int i;
    for (i = 0; i<2; i++)
    {
        scanf("%[^\n]s", str);
        printf("%s\n", str);
  
        // used to clear the buffer
        // and accept the next string
        fflush(stdin);
    }
    return 0;
} 

Input:

geeks
geeksforgeeks

Output:

geeks 
geeksforgeeks

Is it good to use fflush(stdin)?

Although using “fflush(stdin)” after “scanf()” statement also clears the input buffer in certain compilers, it is not recommended to use it as it is undefined behavior by language standard. In C and C++, we have different methods to clear the buffer discussed in this post.

#include <stdio.h>
#include <string.h>

int main () {

   char buff[1024];
   
   memset( buff, '\0', sizeof( buff ));
   
   fprintf(stdout, "Going to set full buffering on\n");
   setvbuf(stdout, buff, _IOFBF, 1024);

   fprintf(stdout, "This is tutorialspoint.com\n");
   fprintf(stdout, "This output will go into buff\n");
   fflush( stdout );

   fprintf(stdout, "and this will appear when programm\n");
   fprintf(stdout, "will come after sleeping 5 seconds\n");
   
   sleep(5);
   
   return(0);
}

memset