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;
}
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)
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, thefflush
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With