While working on a computer science assignment I have had the need to
flush the contents of stdin.
no you didn't!
But the statement
fflush(stdin);
doesn't seem to be working.
[line moved]
Could anyone kindly point out why fflush failed in this situation.
as others have pointed out fflush() only works for (in a sense only
has a meaningful defintion for) output streams. I'm not sure exactly
what you expect but one possibility is you want to skip to the end of
line.
int skip_line (FILE *instream)
{
int ch;
while ((ch = gets(instream)) != '\n' && ch != EOF)
;
return ch;
}
functions like this are tricker to write than you might expect, so
expect a few brickbats to come my way!
On the other hand:
char s[80];
gets(s);
oooH! NEVER DO THAT
gets() is borken. It has no way to indicate how big its buffer is.
(fgets() can be used instead, though it doesn't do quite the same
thing as gets(), read the documentation).
[gets()] does seem to be working provided that whatever is in
the stdin is not longer than 80 characters.
and if it is... where do those extra characters go? On most systems
all over your other data. This is the way in for an amazing number of
virii and other malware.
http://en.wikipedia.org/wiki/Conficker
(ok, I don't know it was gets(), but it *was* a buffer overflow!)
You may want to read this
http://c-faq.com/
Particularly:-
12.26a How can I flush pending input so that a user's typeahead isn't
read at the next prompt? Will fflush(stdin) work?
12.26b If fflush won't work, what can I use to flush input?
12.23 Why does everyone say not to use gets()?
In fact read all of section 12. Then read all of the FAQ. Some you
might not understand or haven't studied yet and some may seem over
picky. Re-read when you learn a little more C and you'll appreciate it
more.
--
A ruby trembled. Two tourmaline nets failed to rectify the laser beam.
A diamond noted the error. Both the error and the correction went into
the general computer.
Corwainer Smith "The Dead Lady of Clown Town"