fflush(stdin) in LINUX
2 posters
Page 1 of 1
fflush(stdin) in LINUX
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);
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
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);
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
Re: fflush(stdin) in LINUX
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)....
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
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum