471,073 Members | 1,172 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,073 software developers and data experts.

rewinding stdin

gc
I was having trouble getting fgets to read a string from stdin, it was
reading a '\n' already in the buffer.
Someone told me to rewind stdin before calling fgets. It works, but is
it permissible?
Nov 13 '05 #1
2 9516
gu**********@yahoo.com (gc) wrote:
I was having trouble getting fgets to read a string from stdin, it was
reading a '\n' already in the buffer.
This is usually caused by mixing calls to *scanf() and fgets(). After
a call to *scanf() it's good practice to drain the input puffer up to
the next '\n'. [ Just in case: no, you cannot use fflush(stdin),
fflush() works for output streams only! ]
Someone told me to rewind stdin before calling fgets. It works, but is
it permissible?


Huh? Well, this is possible if, and only if, stdin is associated with a
RealFile(tm): rewind() sets the file position indicator for the stream
to the beginning of the file - you will start off once again. And, of
course, rewind() won't work if stdin is associated with an interactive
device - or do you know a way to rewind your keyboard? ;)

As mentioned above: it is advisable to drain the input buffer after
calls to *scanf() in order to resync your input stream before subsequent
read operations.

Example:

int c;
while ( ( c = fgetc( stdin ) != EOF ) && ( c != '\n' ) )
/* empty loop body */;
Addition:

If you want to push back one character into the input stream, you
may make use of the ungetc function. But be aware that only _one_
character of pushback is guaranteed by the standard.

Regards

Irrwahn
--
6 * 9 = 42 (base 13)
Nov 13 '05 #2
Irrwahn Grausewitz <ir*****@freenet.de> wrote:

<SNIP>
Ooops...
Works better when parantheses match:
while ( ( c = fgetc( stdin ) != EOF ) && ( c != '\n' ) )


while ( ( ( c = fgetc( stdin ) ) != EOF ) && ( c != '\n' ) )

--
6 * 9 = 42 (base 13)
Nov 13 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

11 posts views Thread by Thomas Matthews | last post: by
reply views Thread by lickspittle | last post: by
3 posts views Thread by Harayasu | last post: by
6 posts views Thread by Charlie Zender | last post: by
6 posts views Thread by ccdrbrg | last post: by
24 posts views Thread by Olaf \El Blanco\ | last post: by
reply views Thread by Gabriel Genellina | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.