Rob said:
Given the code:-
r = sscanf (s, "%lf", x);
What is the correct output if the string s is simply "-" ?
If "-" is considered the beginning of a number, that has been
cut-short then the correct output is that r = EOF. If it is taken to
be a letter in the stream, then the output should be r = 0, as far as
I can see. My compiler gives EOF.
Does the standard specify which is correct?
Haven't seen a reply in the several hours since I first
saw the message, so (fools rush in ...) I'll hazard a guess.
The Standard speaks of two sorts of failure for *scanf()
directives: "matching failure," which amounts to an input
sequence that doesn't satisfy the syntax required by the
directive, and "input failure," meaning that the source of
input characters dried up -- for the stream-input versions
this means EOF was sensed, and for sscanf() it means the
scan reached the end of the string. On a matching failure,
*scanf() stops operating and returns the number of items
already matched and converted (0, in your example), while
for an input failure *scanf() returns EOF.
So the question boils down to this: When "%lf" processes
"-", is the failure a matching failure or an input failure?
One point of view considers it a matching failure. The
characters for "%f" are supposed to be something strtod() would
swallow: an optional all-whitespace prefix, an optional sign,
and then a character string resembling a floating-point constant
as written in C source code. The string "-" doesn't match this
description (the floating-point constant is missing), so it could
be called a matching failure.
The other viewpoint holds that no "mismatch" was detected
before end-of-string, so it's an input failure. The sequence
of characters is perfectly good as the prefix of a valid match,
and the only thing preventing a complete match is the fact that
no more input was available. Hence (says this argument), the
operation ends with an input failure rather than a matching
failure, and EOF is the correct return value.
IMHO the Standard is not entirely clear about which argument
is correct: is an incomplete prefix a failure to match, or a
failure of the input source? To me, the language of the Standard
doesn't shine enough light into this dark corner -- but if anyone
happens to have a torch to hand, I'd welcome illumination ...
Trying to put myself in the place of an implementor, I'd
imagine the input failure (EOF) outcome would be "more natural,"
but I don't think the Standard's language actually says so in
so many words.
The fool has rushed in; tread, o ye angels!