Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fflush() is not working in Linux

Tags:

c

linux

gcc

I used the fflush() in Linux GCC but it did not work. Are there any alternatives for that function? Here is my code:

#include<stdio.h>
void main()
{
  char ch='y';
  while(ch=='y')
  {
    int a;
    printf("Enter some value:");
    scanf("%d",&a);
    fflush(stdin);
    printf("Do you want to continue?");
    scanf("%c",&ch)
  }

The output that I got is:

Enter some value: 10

Then the program ends. That's all. What can I do in Linux? Is there an alternative function?

like image 765
sundar Avatar asked Jun 26 '13 11:06

sundar


People also ask

What is Fflush in Linux?

The fflush() function is the abbreviation of the “flush file buffer”, as it is clear from its name that its function is to clear some content. In C programming, it is used to clear the buffer so that the output stream(stdout) can display the output.

How do you use the Fflush function?

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.

Which element is passed to Fflush ()?

The argument passed to fflush() may be a null pointer. In this case, fflush() flushes the output buffers of all the program's open streams. The fflush() function does not close the file, and has no effect at all on unbuffered files (see “Files” in Chapter 13 for more information on unbuffered input and output).


1 Answers

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

like image 102
Mathuin Avatar answered Oct 26 '22 00:10

Mathuin