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()) != '
' && 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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…