fflush(stdin) in LINUX

Go down

fflush(stdin) in LINUX

Post  goldberg on Sat Aug 30, 2008 8:12 am

Suppose you type the following program in Linux and then Compile it using a gcc compiler
int n;
char str[80];

printf("enter a number: ");
scanf("%d", &n);
printf("enter a string: ");
gets(str);
printf("you typed %d and \"%s\"\n", n, str);

cheers
but the compiler seems to be skipping the call to gets()!
This is just an example
There are other cases too..

Most of the people might be knowing why it happens
This is exclusively for many 2nd yrs who face this problem
It has something to do with fflush
but fflush is not defined for input streams in LINUX
So tell why this happens and provide the best possible solution for it

goldberg

Posts : 8
Join date : 2008-08-11

View user profile

Back to top Go down

Re: fflush(stdin) in LINUX

Post  vijay on Tue Sep 02, 2008 4:16 pm

the reason is....suppose this is the input...
123
motilal nehru
here..scanf() reads a integer and stops when it encounters the new line at the
end of 123..so n = 123 and "\n" is still in the stdin..
now when gets() is called, read from stdin returns a new line and gets() returns
storing a empty string in variable "str"..so input "motilal nehru" is never read....
and it seems as if gets() isn't called....

yeah..fflush() is only for output streams....better way might be to read and
discard useless chars from stdin....i.e use a empty call to getchar() to get rid
of that new line or something like
while( getchar() == '\n' )
;

UNIX system specific call is to use tcflush(3)....

vijay

Posts : 6
Join date : 2008-08-18

View user profile

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum