How to clear stdin before getting new input?

How to clear stdin before getting new input?
.. so I need something with the same functionality.

With portable C this is not possible.


Instead suggest a different (and more usual C) paradigm:
Insure previous input functions consumes all the previous input.

fgets() (or *nix getline()) is the typical approach and solves most situations.

Or roll your own. The following reads an entire line, but does not save extra input.

int mygetline(char *buf, size_t size) {
  assert(size > 0 && size <= INT_MAX);
  size_t i = 0;
  int ch;
  while ((ch = fgetc(stdin)) != EOF) {  // Read until EOF ...
    if (i + 1 < size) {
      buf[i++] = ch;
    }
    if (ch == '\n') {  // ... or end of line
      break;  
    }
  } 
  buf[i] = '\0';
  if (i == 0) { 
    return EOF;
  }
  return i;
}

Leave a Comment