rewinding stdin

G

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?
 
I

Irrwahn Grausewitz

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
 
I

Irrwahn Grausewitz

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

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,079
Messages
2,570,574
Members
47,207
Latest member
HelenaCani

Latest Threads

Top