How to clear stdin before getting new input?
Solution 1:
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;
}
Solution 2:
From a similar question, Use poll() with fds.fd set to 0 (stdin), fds.events set to POLLIN, nfds set to 1, and timeout set to zero. After calling poll(), fds.revents will be set to zero if the buffer is empty, and to POLLIN otherwise.
struct pollfd fds = {0, POLLIN, 0};
poll(&fds, 1, 0);
if(fds.revents == POLLIN}
printf("stdin buffer is not empty");
This solution will work on posix-compliant systems, but not Windows. Use select() for portability.