Can fseek(stdin,1,SEEK_SET) or rewind(stdin) be used to flush the input buffer instead of non-portable fflush(stdin)?

最后都变了- 提交于 2019-12-04 03:17:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!