Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is the only portable idiom to use:

while((c = getchar()) != '
' && 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...