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.

Razib
  • 10,965
  • 11
  • 53
  • 80
  • There is some useful scanf related information here: http://stackoverflow.com/questions/1247989/how-do-you-allow-spaces-to-be-entered-using-scanf – iammowgli May 22 '15 at 03:28
  • You can see more detail about `scanf()` function in [here](http://www.cplusplus.com/reference/cstdio/scanf/). Read description of `format`, answer of your question is explained so clearly. – Hoang Pham May 22 '15 at 06:36

3 Answers3

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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
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);
Razib
  • 10,965
  • 11
  • 53
  • 80
  • @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. – iammowgli May 23 '15 at 04:36
  • 1
    @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. – KajolK May 23 '15 at 15:11
  • @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'`. – chux - Reinstate Monica May 23 '15 at 15:26
0

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

scanf("%f ");

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

Arun A S
  • 6,421
  • 4
  • 29
  • 43
Hong Seok
  • 61
  • 4