Reputation: 91
For each of the following pairs of
scanf
format strings, indicate whether or not the two strings are equivalent. If they're not, show how they can be distinguished:(b)
"%d-%d-%d"
versus"%d -%d -%d"
So in this case, my answer was that they were not equivalent. Because non-white-space characters except conversion specifier which start with %
, cannot be preceded by spaces, it will not match with the non-white-space character. So in the first case, no spaces will be allowed after the first and second integer, while in the second case, any number of spaces will be allowed after the first 2 integers.
But I saw that the book had a different answer. It said that they were both equivalent to each other.
Is this the mistake of the book? Or am I just wrong with the concept of format string in the scanf
function?
Upvotes: 5
Views: 305
Reputation: 5517
The book is wrong. As per the specification of the scanf()
:
So in first case when scanf
arrives to the %d
and gets the input, next is the -
which means that scanf
will expect next in the stream to see the non-whitespae
character -
and not any other whitespace
character. So the legal input is 1- 2
, but not 1 -2
In the second case, after first %d
, scanf
will allow the whitespace
and than will arrive to non-whitespace
, so it will allow the input 1 - 2
by the above definitions.
Upvotes: 3
Reputation: 153338
"%d-%d-%d"
differs from "%d -%d -%d"
and the difference has nothing to do with "%d"
.
Format "-"
scans over input "-"
and stops on the first space of input " -"
.
Format " -"
scans over inputs "-"
and " -"
as the " "
in the format matches 0 or more white-space characters in the input.
A directive composed of white-space character(s) is executed by reading input up to the first nonwhite-space character (which remains unread), or until no more characters can be read. The directive never fails. C17dr § 7.21.6.2 5
Had the question been: "%d-%d-%d"
versus "%d- %d- %d"
,
These 2 are functionally identical.
We would need to dive input arcane stdin
input errors to divine a potential difference.
Upvotes: 1