Jonathan  Leon
Jonathan Leon

Reputation: 3

fflush\flushall()\_flushall() and etc won't clear buffer in C

In all the programs I'm required to do for a project I encounter an input buffer problem, so far I cleaned it with a while loop but I've been told now not to do so (You can see it commented out).

I tried using flushall(), _flushall() and all the alternatives that Visual Studio offers me but none of them cut it.

What am I doing wrong?

    while (speed <= 0 || distance <= 0 || (distance == -1 || speed == -1))
    {

        scanf(" %d %d", &distance, &speed);
        //while (getchar() != '\n');


   }

Upvotes: 0

Views: 2090

Answers (2)

Peter
Peter

Reputation: 36617

The real technique, in most circumstances, is not to try to flush stdin at all.

To do that, it is necessary to interact with stdin in the same way, every time. In practice, that normally amounts to not mixing styles of input.

If using formatted input (like scanf()), never use line-oriented input (e.g. fgets()) or character oriented input (e.g. getc()) on the same stream. Similarly, if using fgets() to read, never use formatted input or character-oriented input on the same stream.

And so on.

The reason is that different styles of input respond differently to some specific characters - particularly to newline and whitespace. When you mix those styles of input, there are unwanted interactions. scanf(), for example, will often stop reading if it encounters a newline ('\n'), and leave that newline in the stream. fgets() on the other hand will also stop as soon as it reaches a newline, but remove that newline from the stream. Hence if there is a scanf() call followed by a fgets( ..., stdin), the fgets() call will often return immediately - without reading the data that was expected.

Furthermore, if using scanf(), it is necessary to be careful with choice of format strings, to avoid some interactions between subsequent calls as well.

Upvotes: 2

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215517

The stdio "flush" operation (fflush) has nothing to do with "clearing buffers". It merely causes data buffered for write to be written out to the actual file. If you want to discard input (e.g. to the end of the line), write code to discard input.

Upvotes: 2

Related Questions