C language scanf - fflush (stdin) - not working

When I use scanf more than once, the program doesn't wait for another input. Instead, it comes out of

I found out that I can put a space before the conversion specifier in scanf functions - yes, which solved the problem, and I assume it has to do with the input stream, that is - if its newline character in the input stream scanf will use it immediately.

scanf(" %f", &value);

      

But if that's the case, why don't I use fflush (stdin)? I tried it but it doesn't work.

#include <stdio.h>

int main(void)
{
    float value;
    char ch;

    printf("input value: ");
    scanf("%f", &value);
    fflush(stdin);
    printf("input char: ");
    scanf("%c", &ch);

    return 0;
}

      

+3


source to share


2 answers


fflush()

used to flush output buffers. Since you are trying to flush the input buffer this can lead to undefined behavior.

Here's a question that explains why it's not good practice:



Using fflush (stdin)

+8


source


AS in standard document C11

, chapter 7.21.5.2, fflush()

function, (emphasis mine)

int fflush(FILE *stream);

If stream

points to an output stream or update stream in which the last operation was not entered, the function fflush

causes any unwritten data for that stream to be delivered to the host environment to be written to a file; , the behavior is undefined.

therefore, mostly using fflush(stdin);

, undefined The behavior .

To use your purpose, when using the format specifier, %c

you can rewrite your code as



scanf(" %c", &ch);
       ^
       |
   notice here

      

leading spaces before %c

skipping all whitespace characters (including those \n

saved by pressing the previous key ENTER) and reading the first non-whitespace character.

Note: as %d

and %f

qualifiers already internally ignore leading spaces, you don't need to explicitly specify in these cases.

+5


source







All Articles