what is the purpose of putting a space in scanf like this scanf(" %c",&ch) in place of scanf("%c",&ch)? -


this question has answer here:

what purpose of putting space in scanf

scanf(" %c",&ch)  

in place of

scanf("%c",&ch)? 

also input buffer in fflush(stdin)?

because space before %c ignores whitespace. *scanf family of functions ignore whitespace before % default except %c, %[ , %n. mentioned in c11 at:

7.21.6.2.8

input white-space characters (as specified isspace function) skipped, unless specification includes [, c, or n specifier.

to complete, here's part says whitespace ignored:

7.21.6.2.5

a directive composed of white-space character(s) executed reading input first non-white-space character (which remains unread), or until no more characters can read. directive never fails.


regarding second question, fflush(stdin) causes undefined behavior , must not used (emphasis mine):

7.21.5.2.2

if stream points output stream or update stream in recent operation not input, fflush function causes unwritten data stream delivered host environment written file; otherwise, behavior undefined.


Comments