what is the purpose of putting a space in scanf
like this
scanf(" %c",&ch)
in place of
scanf("%c",&ch)?
Also what is input buffer in fflush(stdin)
?
Because the space before %c
ignores all whitespace. *scanf
family of functions ignore all whitespace before any %
by default except for %c
, %[
and %n
. This is mentioned in C11 at:
7.21.6.2.8
Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier.
To be complete, here's the part that says all whitespace will be ignored:
7.21.6.2.5
A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails.
Regarding your second question, fflush(stdin)
causes undefined behavior and must not be used (emphasis mine):
7.21.5.2.2
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.
what is the purpose of putting a space in scanf like this scanf(" %c",&ch) in place of scanf("%c",&ch)?
So that scanf
would ignore all spaces before the first non-space character is encountered in the stream.
Also what is input buffer in fflush(stdin)?
What you input into the console will exist in the stdin
stream.
Don't flush that stream however, it's undefined behavior.
If you want to discard characters entered after scanf
is called, you can read and discard them.
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