Fflush() in Multiple Scanf calls

What is the requirment of using fflush() in multiple scanf calls.

Questions by Gaurav Kumar   answers by Gaurav Kumar

Showing Answers 1 - 15 of 15 Answers

Fflush is mainly used to cleanup all pipelines and buffer which are used during the storage of data or writing the data; it is necessary because it may block pipelines and may be responsible undesired output. It is good programming approach that you flush pipeline after writing data, in case of Java programming it is must to flush data otherwise it will not go properly into destination file.

suman680

  • Sep 1st, 2009
 

When we take some name, age, class from user using scanf then at first when we take name and after age then some time the age place is skip and user can not assigned any value there. Reason behind it only is buffer. After giving name by user there some change in buffer to clear this buffer we can use fflush().

  Was this answer useful?  Yes

kbjarnason

  • Jul 1st, 2010
 

There is no requirement to use fflush in multiple scanf calls.  fflush operates exclusively on output streams, thus has no relation to scanf, which is an input function.

That said, if one is using multiple _prompted_ scanf calls, one should flush after the prompts, to ensure they are seen.  That is:

printf( "Enter your name" );
scanf( "%s", buff );

is not guaranteed to display the prompt before attempting to get the user's input.  To ensure the prompt is displayed, you need to either end the prompt with a n, or insert a ffflush call:

printf( "Enter your name" );
fflush( stdout );
scanf( "%s", buff );

If, for some reason, scanf does not "eat" all the input (conversion failure, etc) you may in fact need to flush the input stream, partially or entirely, but fflush is not the tool for this.

  Was this answer useful?  Yes

The behavior of fflush() is not defined for input streams.  If you need to clear extraneous or garbage data from an input stream, you'll have to use some other method.  When dealing with non-binary input, I just read everything as text using fgets() or fgetc() and then use either sscanf() or strtol()/strtod() to do any conversions. 

Like kbjarnason said, you might have to use fflush() after a prinf() to make sure a prompt gets displayed, but you shouldn't have to use it after a scanf() call.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions