Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between different scanf formats [duplicate]

I'm currently prepping myself for programming school by going through the textbook. There's this particular question which I don't understand and the textbook doesn't give the answer.

PS: I've learned some C++/C# online, but never go through proper-taught programming classes, so I'm struggling with some of the concepts.

Q: For each of the following pairs of scanf format strings, indicate whether or not the two strings are equivalent. If they are not, show how they can be distinguished.

A) "%d" versus " %d"
B) "%d-%d-%d" versus "%d -%d -%d"
C) "%f" versus "%f "
D) "%f,%f" versus "%f, %f"

First off, I don't even understand what the question is asking. What does the textbook mean by whether or not the 2 strings are 'equivalent'?

If they are, could someone explain the differences and possibly show me how they can be distinguished?

like image 830
Jason_Kalmatos Avatar asked Oct 18 '22 06:10

Jason_Kalmatos


1 Answers

Let us try A first: "%d" versus " %d", they are equivalent format strings for scanf().

" " will do the following. It never fails.
1) Scan and discard (skip) optional white-space.
2) After reading a non-white-space or end-of-file, if not (EOF), the last character read is put back into stdin.

"%d" itself will attempt 3 things (It can fail)
1) Scan and discard (skip) optional white-space.
2) Scan and convert numeric text representing a decimal integer.
3) After reading a non-numeric text or end-of-file, if not (EOF), the last character read is put back into stdin.

" %d" does both the above. It is the same result of just doing the 2nd with "%d".

With *scanf() specifiers note:

Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier. C11 §7.21.6.2 8


B, C, D differences?

Mouse over for hint 1:

A " " before a scanf() specifier, except the 3 noted above, is an equivalent scanf() format as without it.

Mouse over for hint 2:

Only 1 of 3 equivalent.

Mouse over for hint 3:

Consider inputs:
"123 -456-789"
"123.456 x" What is the next character to be read?

B) "%d-%d-%d" versus "%d -%d -%d"
C) "%f" versus "%f "
D) "%f,%f" versus "%f, %f"

Answer:

Awww, Do you really want to be given the answer?

like image 62
chux - Reinstate Monica Avatar answered Oct 21 '22 06:10

chux - Reinstate Monica