Search code examples
cflushfflush

Is this the proper way to flush the C input stream?


Well I been doing a lot of searching on google and on here about how to flush the input stream properly. All I hear is mixed arguments about how fflush() is undefined for the input stream, and some say just do it that way, and others just say don't do it, I haven't had much luck on finding a clear efficient/proper way of doing so, that the majority of people agree on.. I am quite new at programming so I don't know all the syntax/tricks of the language yet, so my question which way is the most efficient/proper solution to clearing the C input stream??

  1. Use the getchar() twice before I try to receive more input?

  2. Just use the fflush() function on the input? or

  3. This is how I thought I should do it.

    void clearInputBuf(void);  
    void clearInputBuf(void) 
    { 
          int garbageCollector; 
          while ((garbageCollector = getchar()) != '\n' && garbageCollector != EOF) 
          {}
    }
    

So, whenever I need to read a new scanf(), or use getchar() to pause the program I just call the clearInputBuf.. So what would be the best way out of the three solutions or is there a even better option?


Solution

  • All I hear is mixed arguments about how fflush() is undefined for the input stream

    That's correct. Don't use fflush() to flush an input stream.

    (A) will work for simple cases where you leave single character in the input stream (such as scanf() leaving a newline).

    (B) Don't use. It's defined on some platforms. But don't rely on what standard calls undefined behaviour.

    (C) Clearly the best out of the 3 options as it can "flush" any number of characters in the input stream.

    But if you read lines (such as using fgets()), you'll probably have much less need to clear input streams.