I have read about 5-10 different advices how to clear stdin, but none of them suits my needs. The thing is that fflush(stdin)
worked perfectly at my computer, but unfortunately it doesn't seem to work everywhere, so I need something with the same functionality. Every other way I tried clears stdin when it is not empty but requires user input when stdin IS empty, which means it requires input in a moment I dont want to get any (+ it discards it anyway).
The question is: Can I somehow make sure, that stdin
IS empty before I require user input? (and if not, THEN and only then clear it somehow?)
something like:
if (stdin is NOT empty)
while (getchar() != '\n')
continue;
EDIT: the thing is that I load characters from stdin
one by one and at some point, a part of the input from previous iteration might or might not get discarded. either way, I need to have clear stdin
before I ask the user for another input to be processed. Clearing the buffer itself is not such a big deal, the problem is what happens when the input is empty when the program gets to the point of clearing stdin
, because in that moment the program needs another input which is going to be eaten by the clearing function. Thats what I want to get rid of. (when I could use fflush(stdin);
I just knew, that for the next line of my program the stdin
WILL be empty no matter what, no questions asked...)
fflush(stdin)
is UB. – Yong./myprog </dev/random
; will it ever see the end of its stdin stream? – Ichthyoidapt-get
program does this, intentionally. See Prevent sudo, apt-get, etc. from swallowing pasted input to STDIN – Delude