简体   繁体   中英

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');


   }

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 (eg to the end of the line), write code to discard input.

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 (eg fgets() ) or character oriented input (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM