954,479 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

how to properly flush the input stream (stdin)

0
By jephthah on Jun 10th, 2009 11:19 am

too many new and intermediate users of C attempt to use the command fflush(stdin) to "flush the input buffer". this is patently wrong.

the rule is (and click if you don't believe me) : NEVER USE "FFLUSH()" ON INPUT STREAMS SUCH AS "STDIN"

here is one method of properly flushing extra (and unwanted) characters from the stdin input stream. the code is written as a macro, and requires a character array to collect excess (junk) input. the macro will also ensure the newline character is stripped.

the intended use is in conjunction with fgets. for example:

char userInput[8]; // change array size to any arbitrary value

    printf("input a string and hit <enter>.  A maximum of %d characters will be recorded.\n",sizeof(userInput)-1);

    fgets(userInput,sizeof(userInput),stdin);
    FLUSH_STDIN(userInput);    // strip newline, flush extra chars

    printf("the first %d characters are \"%s\", any others have been discarded.\n",strlen(userInput),userInput);
#define FLUSH_STDIN(x) {if(x[strlen(x)-1]!='\n'){do fgets(Junk,16,stdin);while(Junk[strlen(Junk)-1]!='\n');}else x[strlen(x)-1]='\0';}

char Junk[16]; // buffer for discarding excessive user input, 
               // used by "FLUSH_STDIN" macro

wow, dude, this snippet rocks! A+++ would read again!

jephthah
Posting Maven
2,587 posts since Feb 2008
Reputation Points: 2,143
Solved Threads: 179
 

Rofl :]

William Hemsworth
Posting Virtuoso
1,591 posts since Mar 2008
Reputation Points: 1,429
Solved Threads: 129
 

It's good. ;)

The one I like moves the stream pointer for the keyboard - very elegant, but everybody asks WTF is THAT?

Adak
Nearly a Posting Virtuoso
1,479 posts since Jun 2008
Reputation Points: 425
Solved Threads: 185
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You