Find the answer to your Linux question:
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? ...
  1. #1
    Just Joined! garry_3peace's Avatar
    Join Date
    Oct 2008
    Posts
    67

    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.

  2. #2
    Linux Engineer wje_lf's Avatar
    Join Date
    Sep 2007
    Location
    Mariposa
    Posts
    1,192
    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.

  3. #3
    Just Joined! garry_3peace's Avatar
    Join Date
    Oct 2008
    Posts
    67
    Ah... yes, yes.. I understand your way.
    Thank you very much for the suggestion....

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...