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

Since I found that fflush(stdin) not a portable way to deal with the familiar β€œnew line hiding in input buffer” problem, I used the following when I should use scanf :

 while((c = getchar()) != '\n' && c != EOF); 

But today I came across this line, which I noted from cplusplus.com on fflush :

fflush () ... in files open for updating (i.e. open for reading and writing), the stream must be flushed after the output operation before performing the input operation. This can be done either by permutation (fseek, fsetpos, rewind), or by explicitly calling fflush

In fact, I have read this many times. Therefore, I want to confirm whether I can simply use any of the following actions before scanf() to accomplish 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 efficient to flush the buffer, right?

The error . I should have mentioned fseek(stdin,0,SEEK_SET) if we are talking about stdin , since we cannot use any offset other than 0 or the one returned by ftell() in this case.

+6
source share
1 answer

This is the only portable idiom to use:

 while((c = getchar()) != '\n' && c != EOF); 

Several threads, including this , explain why feesk usually doesn't work. for the same reasons, I doubt rewind will work either, in fact the man page says it is equivalent:

 (void) fseek(stream, 0L, SEEK_SET) 
+3
source

Source: https://habr.com/ru/post/945502/


All Articles