J
Johnathan Doe
I'm trying to find a way to reliably peek at stdin, and if anything's
waiting, flush stdin so that it clears the stream ready to wait for a
character.
The problem I have is that in an application, if I call say scanf() to
get some input, occasionally the newline is still left hanging around in
the buffer. If there's any junk left over in stdin after getting input
I'd like to clear it out. And then when going to read input again
later, check for any junk and clear it out before prompting and
attempting to read input.
I've found a way to do this quite well by using:
scanf("%c%*c", &ch);
which gets a menu choice of a single character, and sucks up the newline
still in the stream. But, if any extra stuff is entered, this is not
very robust. It's all still left in the input stream. Because most of
my programs run in blocking mode, I can sit there in a loop and read
everything until stdin drains out. I've tried going into non-blocking
mode to "peek" at anything that might be there, get it, and then return,
but I couldn't make it work. It also seems like a bit of a nasty hack.
Any ideas?
Many thanks for your help.
Johnathan
waiting, flush stdin so that it clears the stream ready to wait for a
character.
The problem I have is that in an application, if I call say scanf() to
get some input, occasionally the newline is still left hanging around in
the buffer. If there's any junk left over in stdin after getting input
I'd like to clear it out. And then when going to read input again
later, check for any junk and clear it out before prompting and
attempting to read input.
I've found a way to do this quite well by using:
scanf("%c%*c", &ch);
which gets a menu choice of a single character, and sucks up the newline
still in the stream. But, if any extra stuff is entered, this is not
very robust. It's all still left in the input stream. Because most of
my programs run in blocking mode, I can sit there in a loop and read
everything until stdin drains out. I've tried going into non-blocking
mode to "peek" at anything that might be there, get it, and then return,
but I couldn't make it work. It also seems like a bit of a nasty hack.
Any ideas?
Many thanks for your help.
Johnathan