How to validate input?
Chris Torek
chris at mimsy.umd.edu
Sat Dec 1 01:10:52 AEST 1990
In article <2195.2754fcc2 at iccgcc.decnet.ab.com>
browns at iccgcc.decnet.ab.com (Stan Brown) writes:
[regarding *scanf("%o%c"...) with input beginning with `8']
>The standard says sscanf stops converting when it finds an invalid
>character, so at first blush we expected num_fields to be 0 because the
>first character in the string isn't an octal digit. But working through
>the definition of %o, which is in terms of strtoul( ), and in working
>through the definition of the latter, we find that a "base part" of no
>characters is considered valid.
I got a different answer when I wrote my `scanf' innards: only a few
formats are allowed to be `empty', and none of the numeric conversion
formats are included in those few. So while "" is a `proper' octal
number to strtoul(), it is not a `proper' octal number to %o and %o
must stop with a matching failure, causing the sscanf call to return 0.
> 2. What is the best way to accomplish what we're trying to
> accomplish, i.e. to check quickly that the user typed a valid
> octal number and nothing else?
I prefer
char *cp; unsigned long value;
value = strtoul(buf, &cp, 8);
if (cp == buf || *cp != '\0')
... input value was invalid ...;
but I believe the sscanf described in the parent article should also work.
--
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 405 2750)
Domain: chris at cs.umd.edu Path: uunet!mimsy!chris
More information about the Comp.lang.c
mailing list