rahul tyagi
rahul tyagi

Reputation: 643

Alternate method for clearing input buffer in c

Is there any other method to clear the input buffer in c withut using

  fflush();

or

  while(getchar()!='\n');

Because i have read it everywhere and cant find any other way to do it.

Upvotes: 2

Views: 14054

Answers (3)

Spikatrix
Spikatrix

Reputation: 20244

Another method to clear the input buffer (stdin) would be to use

scanf("%*[^\n]");
scanf("%*c");

%*[^\n] instructs scanf to scan everything until a new-line character(\n) and then discards it. The %*c tells scanf to scan and discard a single character which in this case will be the newline character.

Upvotes: 2

chux
chux

Reputation: 153547

Using fgets() as suggester @unwind best approach.

To flush to the end of the line.

void FlushStdin(void) {
  int ch;
  while(((ch = getchar()) !='\n') && (ch != EOF));
}

If stdin is all ready flushed to the end-of-line, calling FlushStdin() or other posted scanf(), fgetc() solutions, will flush to the end of the next line.

Note scanf("%*[^\n]%*1[\n]"); does not work if the next char is '\n'.

Upvotes: 2

unwind
unwind

Reputation: 399871

The best solution is to not depend on the input buffer's state so much.

Read input as whole lines, using fgets(), then parse those. Don't use e.g. scanf() to read individual values, since it interacts with the buffer in annoying ways.

Upvotes: 2

Related Questions