Search code examples
cstdin

How to properly flush stdin in fgets loop


I have found the example of clearing stdin using while((c = getchar()) != '\n' && c != EOF) on here a few times, and tried to use it in a loop that gets input via fgets. I need to flush, since the loop takes the \n character from the last input and runs with it again.

So what happens is that I have to press enter twice now. Why is this happening, and how can I fix this?

#define BUFFER_LIMIT 50
do
{
  int c;
  while ((c = getchar()) != '\n' && c != EOF);

  printf("console> ");
  fgets(input_buffer, BUFFER_LIMIT-1, stdin);

  if(do_something(input_buffer))
    break;
} while(strncmp(input_buffer, "quit", 4) != 0);

Solution

  • So what happens is that I have to press enter twice now. Why is this happening, and how can I fix this?

    Well, that is what your code is doing - it first reads char-by-char until it finds newline. Then it calls fgets() which will... well, read until it finds a newline (probably char-by-char, but, also possibly in some other way).

    You could try fflush(stdin), but that is not guaranteed to do what you want (it only gives guarantees for output buffers, not for input).

    Also, you may try setbuf(stdin, NULL) which should disable buffering on standard input, so there would be nothing to flush. I tried this a few times on different systems and it worked, but documentation for this function is not 100% clear on this.