Thursday, 17 August 2017

c - I am not able to flush stdin




How to flush the stdin??



Why is it not working in the following code snippet?



#include 
#include
#include
#include


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?


Answer



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

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...