What is the use of fflush() function?

Showing Answers 1 - 3 of 3 Answers

mswaroop

  • Sep 5th, 2007
 

Suppose we read a sentence using scanf e.g. "My name is ABC" in a string.
Printing this string using a printf statement prints "My".

Go for another successive scanf.
It reads from the input stream... which still is having "name is ABC".
Hence pritning the string this time shows "name".

Solution to this is a fflush statement after first printf.
This clears the input stream.

As a result next scanf reads fresh string passed to it at the command prompt.

Code:

 n=2;
 while (n)
 {
  printf( "Input a sentencen" );
  scanf( "%s", string );
  printf( "First word is: %sn", string );
  fflush ( stdin );                                     //comment it once and see the difference
  n--;
 }

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