Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()) != '\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.

like image 998
Jugni Avatar asked May 21 '13 14:05

Jugni


People also ask

Can you flush Stdin?

The function fflush(stdin) is used to flush or clear the output buffer of the stream. When it is used after the scanf(), it flushes the input buffer also. It returns zero if successful, otherwise returns EOF and feof error indicator is set.

Does Fseek work with stdin?

When it's pointing to stdin, fseek does not seem to work. By that, I mean I use it and then use fgetc and I get unexpected results.

What can I use instead of Fflush Stdin?

scanf is a standard library function designed to read data in a fixed format from stdin.

What does it mean by Fflush Stdin?

The function fflush(stdin) is used to flush the output buffer of the stream. It returns zero, if successful otherwise, returns EOF and feof error indicator is set.


1 Answers

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)
like image 94
Shafik Yaghmour Avatar answered Sep 24 '22 10:09

Shafik Yaghmour