Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am not able to flush stdin

Tags:

c

stdin

fflush

How to flush the stdin??

Why is it not working in the following code snippet?

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

int main()
{
        int i=0,j=0, sat;
        char arg[256];
        char * argq;
        argq = malloc(sizeof(char)*10);

        printf("Input the line\n");
        i=read(0, arg, sizeof(char)*9);
        arg[i-1]='\0';
        fflush(stdin);

        i=read(0, argq, sizeof(char)*5);
        argq[i-1]='\0';

        puts(arg);
        puts(argq);

        return 0;
}

Now if i give the input as 11 characters, only 9 should be read but the remaining two characters in the stdin are not flushed and read again in the argq. Why?

Input: 123 456 789

Output: 123 456 89

Why am i getting this 89 as the output?

like image 398
Subodh Asthana Avatar asked Feb 02 '10 20:02

Subodh Asthana


People also ask

Can you flush Stdin?

The function fflush(stdin) is used to flush or clear the output buffer of the stream. When it is used after the scanf(), it flushes the input buffer also. It returns zero if successful, otherwise returns EOF and feof error indicator is set.

How do you flush stdin in Python?

stdout. flush() forces it to “flush” the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so. The sys module provides functions and variables used to manipulate different parts of the Python runtime environment.

Why is Fflush Stdin wrong?

So, if the file stream is for input use, as stdin is, the behaviour is undefined, therefore it is not acceptable to use fflush() for clearing keyboard input. As usual, there are some exceptions, check your compiler's documentation to see if it has a (non-portable) method for flushing input.


2 Answers

I believe fflush is only used with output streams.

You might try fpurge or __fpurge on Linux. Note that fpurge is nonstandard and not portable. It may not be available to you.

From a Linux fpurge man page: Usually it is a mistake to want to discard input buffers.

The most portable solution for flushing stdin would probably be something along the lines of the following:

int c;
while ((c = getchar()) != '\n' && c != EOF);
like image 122
jschmier Avatar answered Oct 04 '22 19:10

jschmier


From the comp.lang.c FAQ, see:

  • How can I flush pending input so that a user's typeahead isn't read at the next prompt? Will fflush(stdin) work?
  • If fflush won't work, what can I use to flush input?
like image 40
jamesdlin Avatar answered Oct 04 '22 19:10

jamesdlin