scanf(), field width, inf and nan

Viewed 1747

Per the C standard from 1999, scanf() and strtod() should accept infinity and NaN as inputs (if supported by the implementation).

The descriptions of both functions have peculiar language, which may be open to interpretations.

scanf():

An input item is defined as the longest sequence of input characters which does not exceed any specified field width and which is, or is a prefix of, a matching input sequence.

strtod():

The subject sequence is defined as the longest initial subsequence of the input string, starting with the first non-white-space character, that is of the expected form.

While the latter excerpt appears to be strict in requiring the specific forms of "INF", "INFINITY", "NAN" or "NAN(n-char-sequence-opt)", the former isn't and one would think that the following code should produce infinity and NaN because the field width covers prefixes of matching input sequences:

int r;
double d;
d = 0; r = sscanf("inf", "%2le", &d);
printf("%d %e\n", r, d);
d = 0; r = sscanf("nan", "%2le", &d);
printf("%d %e\n", r, d);

There's also this bit on scanf():

a,e,f,g Matches an optionally signed floating-point number, infinity, or NaN, whose format is the same as expected for the subject sequence of the strtod function. The corresponding argument shall be a pointer to floating.

Is this simply a failure to document that a field width of 2, which is shorter than the expected shortest forms ("inf" or "nan"), does not make the otherwise matching prefixes "in" and "na" valid matches?

2 Answers
Related