fflush(stdin) in LINUX

Post new topic   Reply to topic

View previous topic View next topic Go down

fflush(stdin) in LINUX

Post  goldberg on Sat Aug 30, 2008 2:12 pm

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 10: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

View previous topic View next topic Back to top


Post new topic   Reply to topic
Permissions of this forum:
You cannot reply to topics in this forum