Nguyễn Văn Dũng
Nguyễn Văn Dũng

Reputation: 55

Need help about function scanf in C

I'm reading book "C Programming A Modern Approach" and I see a question: Show how can be distinguished: "%f" vs "%f "(after %f have a space) in function scanf().

Can you help me understanding how does "%f " work.

Upvotes: 0

Views: 81

Answers (3)

Hong Seok
Hong Seok

Reputation: 61

if you use the white-space after %f, that is

scanf("%f ");

the scanf() will skip the line-feed character.

Upvotes: 0

chux
chux

Reputation: 153303

"%f" instructs scanf() to

  1. Scan from stdin and discard white-space until no more input or a non-white-space encountered. Put that char back into stdin.
  2. Scan char that represents a float. Continue until no more input or a non-float char encountered. Put that char back into stdin.

"%f " instructs scanf() to the steps 1 and 2 above and then

  1. Scan from stdin and discard white-space until no more input or a non-white-space encountered. Put that char back into stdin. (just like step 1)

Note: All scanf() format specifiers except "%c", "%n", "%[]" perform step 1 before scanning further.

Upvotes: 3

Razib
Razib

Reputation: 11153

The second one required a space followed by a float you entered. If you have multiple float to take from user then you can write something like -

scanf("%f %f", &f1, &f2);

Upvotes: 0

Related Questions