简体   繁体   中英

How to flush the console buffer?

i have some code that run repetedly :

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

in the next my code is running it doesnt wait for input. i found out that getchar in the seconed time use '\\n' as the charcter. im gussing this is due to some buffer the sdio has, so it save the last input which was "Y\\n" or "N\\n".

my Q is, how do i flush the buffer before using the getchar, which will make getchar wait for my answer?

Flushing an input stream causes undefined behaviour.

int fflush(FILE *ostream);

ostream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

To properly flush the input stream do something like the following:

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;
}

See Why fflush(stdin) is wrong and Flush the input buffer .

As far as I know, flushall is not POSIX. In order to flush a console buffer in a standard way, you can simply use the command:

fflush(NULL);

This topic seems to be a bit old but I hope this can still help the others.

在printf之前使用fflush()和flushall()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM