Results 1 to 3 of 3
Say if we sometime use scanf(), it may skip some of the scanf because of the leftover in the stream. Is there anyway to clear the stream in standard input?
...
- 10-23-2008 #1
Clear stdin stream in Linux
Say if we sometime use scanf(), it may skip some of the scanf because of the leftover in the stream. Is there anyway to clear the stream in standard input?
Usually I use another scanf() to get those left over. But this is not effective. Any suggestion?
Ow btw I ever code in Borland C, and it can use fflush(stdin). But in Linux it can't. I have read somewhere, it states that actually fflush(stdin) is not to clear the stream in standard input, it is only Borland version can do that.
- 10-23-2008 #2
Don't use scanf(). As you have experienced, it gives you unexpected behavior if the input is not exactly as you expect it.
Instead, use fgets() to get a whole line of input (everything up to and including the <ENTER> key) into a string. Then use sscanf() on that string. Note the extra "s" in the function name; it stands for "string", and reminds you that you're scanning not from the input stream (which you accessed via the fgets() function), but from a string.
That way, when you're done decoding what you've wanted from that string, you can simply ignore what's left in the string, what was left in what the user typed before he pressed the <ENTER> key. I think this is what you meant by "clear the stream". Just go back and do another fgets() to get the next line, and parse that line with another sscanf().
Does this make sense?--
Bill
Old age and treachery will overcome youth and skill.
- 10-23-2008 #3
Ah... yes, yes.. I understand your way.

Thank you very much for the suggestion....


Reply With Quote