How to clear the console buffer?

I have a code that repeats:

printf ("do you want to continue? Y / N: \ n");
keepplaying = getchar ();

works in my next code, it does not wait for input. I found out that getchar in secret time uses '\ n' as a charcter. This is due to some buffer that sdio has, so it saves the last input that was "Y \ n" or "N \ n".

my Q, how do I flush the buffer before using getchar, which will make getchar wait for my response?

+3
source share
3 answers

Flushing the input stream causes undefined behavior.

int fflush (FILE * ostream);

ostream , , fflush , , ; undefined.

, :

int main(void)
{
  int   ch;
  char  buf[BUFSIZ];

  puts("Flushing input");

  while ((ch = getchar()) != '\n' && ch != EOF);

  printf ("Enter some text: ");

  if (fgets(buf, sizeof(buf), stdin))
  {
    printf ("You entered: %s", buf);
  }

  return 0;
}

. fflush (stdin) .

+4

fflush() flushall() printf

+1

As far as I know, flushallnot POSIX. To flush the console buffer in the standard way, you can simply use the command:

fflush(NULL);

This question seems a little old, but I hope this helps others anyway.

+1
source

Source: https://habr.com/ru/post/1782982/


All Articles