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