0

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.

2
  • There is some useful scanf related information here: stackoverflow.com/questions/1247989/… Commented May 22, 2015 at 3:28
  • You can see more detail about scanf() function in here. Read description of format, answer of your question is explained so clearly. Commented May 22, 2015 at 6:36

3 Answers 3

3

"%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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

@Nguyen. I believe the only 'spaces' that scanf ignores are: tab, space bar & newline ('enter' key) present in the input stream. When the 'space' is in between format specifiers e.g. scanf("%f %f", ...), it is ignored. But in your second example, there is no other format specifier after the space i.e. ("%f ") ... so it probably expects more data in the stream. Then, after you enter 'something', it attempts to store it in a variable, but since there is only 1 variable 'x' e.g. scanf("%f ", &x), it ignores the 'something' you entered ... and returns.
@Nguyễn Văn-Dũng, why are using slang here. You may down vote if you think some post (answer/question) is incorrect of of low quality. Please don't use slang.
@iammowgli In the default "C" locale, white-spaces are space ' ', form feed '\f', new-line '\n', carriage return '\r', horizontal tab '\t', and vertical tab '\v'.
0

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

scanf("%f ");

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

1 Comment

Note: It will skip a following line-feed character as well an any number of following white-space.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.