Issues with fpurge() and fflush()

It was improper for me to use the fflush() and fpurge() functions for clearing the text input stream. Mea culpa.

First they may not work, which is probably why you're reading this.

Second, and more importantly, C is stream-oriented. The standard library doesn't use interactive input/output functions. Input functions read all input in one big gulp. That input stream includes the Enter key press, which is treated just like any other character. The Enter key doesn't terminate input as far as standard library input functions are concerned.

If you desire interactive programs, then you need to use a library that provides such I/O. For example, the NCurses library contains a battery of interactive text I/O functions as well as direct screen addressing. That approach is perfect, and far better than messing with fpurge() or fflush() to forge a workaround.

That doesn't mean that a solution isn't at hand.

It's possible to weed out text from the stream after the Enter key press. The following function was submitted in my old C language forum several years ago:

void jsw_flush(void)
{
    int ch; /* getchar returns an int */
            /* Read characters until there are none left */
    do
        ch = getchar();
    while(ch != EOF && ch != '\n' );
    clearerr(stdin);    /* Clear EOF state */
}

Use the jsw_flush() function in your code to force all text input to expire and have just what you need remaining in the input stream.

Remember to prototype this function before you use it:

void jsw_flush(void);

Then call the function:

jsw_flush();

as you would any other function, such as fflush() or fpurge() as mentioned inappropriately in the book. The jsw_flush() function neatly dispenses with any excess text input and leaves you with the input you want.

Remember that getchar() returns an int value. This is easy to get wrong because the function's name is getchar, which makes even experienced programs want to declare its variables as char and not int.