S
Simon Biber
The following Example 3 is given in the 1999 C standard for the function
fscanf:
I have tested several implementations and none of them get the last case
right. In no case does fscanf return 0 indicating failure to match
"100ergs of energy" with "%f".
The actual behaviour varies. Some will match '100', leaving the 'e' unread:
quant = 100; strcpy(units, "ergs"); strcpy(item, "energy");
count = 3;
While others will match '100e', leaving the 'r' unread:
quant = 100; strcpy(units, "rgs"); strcpy(item, "energy");
count = 3;
But I am yet to come across an implementation that does what the example
in the Standard specifies. Is this a failure in the implementations or
in the Standard itself?
fscanf:
EXAMPLE 3 To accept repeatedly from stdin a quantity, a unit of
measure, and an item name:
#include <stdio.h>
/* ... */
int count; float quant; char units[21], item[21];
do {
count = fscanf(stdin, "%f%20s of %20s", &quant, units, item);
fscanf(stdin,"%*[^\n]");
} while (!feof(stdin) && !ferror(stdin));
If the stdin stream contains the following lines:
2 quarts of oil
-12.8degrees Celsius
lots of luck
10.0LBS of
dirt
100ergs of energy
the execution of the above example will be analogous to the following
assignments:
quant = 2; strcpy(units, "quarts"); strcpy(item, "oil");
count = 3;
quant = -12.8; strcpy(units, "degrees");
count = 2; // "C" fails to match "o"
count = 0; // "l" fails to match "%f"
quant = 10.0; strcpy(units, "LBS"); strcpy(item, "dirt");
count = 3;
count = 0; // "100e" fails to match "%f"
count = EOF;
I have tested several implementations and none of them get the last case
right. In no case does fscanf return 0 indicating failure to match
"100ergs of energy" with "%f".
The actual behaviour varies. Some will match '100', leaving the 'e' unread:
quant = 100; strcpy(units, "ergs"); strcpy(item, "energy");
count = 3;
While others will match '100e', leaving the 'r' unread:
quant = 100; strcpy(units, "rgs"); strcpy(item, "energy");
count = 3;
But I am yet to come across an implementation that does what the example
in the Standard specifies. Is this a failure in the implementations or
in the Standard itself?