mathieu wrote On 05/09/06 16:03,:
Just for ref. Here is the final solution:
void parse(const char *s)
{
unsigned int val;
char f;
if( !isdigit(s[0])
|| !isdigit(s[1])
|| !isdigit(s[2]))
{
printf( "error\n");
}
else
{
int k = sscanf(s, "%03u%c", &val, &f);
printf( "%d %u %c\n", k, val, f);
}
}
Just for reference, the above code still has an
error that can cause trouble on some systems. The
problem is that `char' can be a signed type or an
unsigned type, whichever the implementation finds
more convenient. On systems where `char' is signed,
it could happen that any or all of s[0] through s[2]
might have negative values. However, isdigit() only
works on non-negative `char' values and on the negative
value EOF; feed it some other negative value, and
unpredictable things will happen. (True, the digits
are known to have positive values -- but if you knew in
advance that you were dealing with digits, you wouldn't
need the isdigit() calls in the first place!)
Fortunately, the cure (for isdigit() and for the
rest of the <ctype.h> functions) is simple: When you
apply one of them to a `char' value, just convert the
`char' to the corresponding non-negative value:
if ( !isdigit( (unsigned char)s[0] ) ...
Note the part about applying the functions to a
`char'. If you apply them to the `int' value returned
by getchar() or getc() or fgetc(), you should not convert
as shown: the value is already either a converted non-
negative character or else it is the negative number EOF.
If it is EOF, you don't want to convert it from negative
to positive; you want to leave it alone. And if it's not
EOF, it's already non-negative and needs no conversion.
But when you're plucking character values from a string
or something, you need the sign conversion.
--
Er*********@sun.com