问题
Since I discovered fflush(stdin)
is not a portable way to deal with the familiar problem of "newline lurking in the input buffer",I have been using the following when I have to use scanf
:
while((c = getchar()) != '\n' && c != EOF);
But today I stumbled across this line which I had noted from cplusplus.com on fflush:
fflush()...in files open for update (i.e., open for both reading and writting), the stream shall be flushed after an output operation before performing an input operation. This can be done either by repositioning (fseek, fsetpos, rewind) or by calling explicitly fflush
In fact, I have read that before many times.So I want to confirm if I can simply use anyone of the following before the scanf()
to serve the same purpose that fflush(stdin)
serves when it is supported:
fseek(stdin,1,SEEK_SET);
rewind(stdin);
PS rewind(stdin)
seems pretty safe and workable to flush the buffer, am I wrong?
Mistake I should have mentioned fseek(stdin,0,SEEK_SET)
if we are talking about stdin
as we can't use any offset other than 0 or one returned by ftell()
in that case.
回答1:
This is the only portable idiom to use:
while((c = getchar()) != '\n' && c != EOF);
Several threads including this one explain why feesk
won't usually work. for much the same reasons I doubt rewind
would work either, in fact the man page says it is equivalent to:
(void) fseek(stream, 0L, SEEK_SET)
来源:https://stackoverflow.com/questions/16672672/can-fseekstdin-1-seek-set-or-rewindstdin-be-used-to-flush-the-input-buffer-i