Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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)?

like image 666
Rahul Kathuria Avatar asked Jun 14 '13 14:06

Rahul Kathuria


2 Answers

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.

like image 85
Shahbaz Avatar answered Sep 19 '22 01:09

Shahbaz


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.

like image 25
user123 Avatar answered Sep 18 '22 01:09

user123