By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,264 Members | 1,761 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,264 IT Pros & Developers. It's quick & easy.

rewinding stdin

P: n/a
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
Share this Question
Share on Google+
2 Replies


P: n/a
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

P: n/a
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.