Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c language scanf - fflush(stdin) - doesnt work [duplicate]

When I use scanf more than one time the program do not wait for another input. Instead it exits

I learned that I could put a blank space before the conversion specifier in the scanf-function - yes that solved the problem and I guess that has to do with the inputstream, that is - if its a newline character in the inputstream the scanf will consume it immediately.

scanf(" %f", &value);

But if its so - why could I not use the fflush(stdin) instead? I have tried but it doesnt 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;
}
like image 790
java Avatar asked Dec 08 '22 03:12

java


2 Answers

fflush() is used for clearing output buffers. Since you are trying to clear an input buffer, this may lead to undefined behavior.

Here is an SO question explaining why this isn't good practice :

Using fflush(stdin)

like image 145
Corb3nik Avatar answered Dec 19 '22 05:12

Corb3nik


AS per the C11 standard document, chapter 7.21.5.2, fflush() function, (emphasis mine)

int fflush(FILE *stream);

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

so, basically, using fflush(stdin); is undefined behaviour.

To serve your purpose, while using %c format specifier, you can rewrite your code as

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

the leading whitespace before %c skips all whitespace like character (including the \n stored by pressing previous ENTER key) and read the first non-whitespace character.

Note: as %d and %f specifiers already internally ignore the leading whitespaces, you don't need to speicy explicitly in those cases.

like image 33
Sourav Ghosh Avatar answered Dec 19 '22 04:12

Sourav Ghosh