How to validate input?

Stan Brown browns at iccgcc.decnet.ab.com
Sat Dec 1 00:02:04 AEST 1990


updated version of this post--previous one cancelled

Here's a puzzler.  We want to have the user type an octal integer at the
keyboard, and find out whether the user actually entered one, and
whether there were any invalid characters on the line.  We use fgets( )
to read a line from the keyboard, then decode it via

    long octa;
    char extra;
    int num_fields;

    num_fields = sscanf(kbd_string, "%lo%c", &octa, &extra);
    if (num_fields == 1) {
	/* do more stuff */
    }
    
The problem is, when the user types just "8" on the line, num_fields is
coming back as 1!

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.

So we have two questions:
    1. To be standard-conforming, should the sscanf call above, with the
       input string containing "8\0", return a value of 0, 1, or 2?
    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?

email suggestions were for %[01234567]

BTW, code must run on VAX and Microsoft C.  This rules out using %n
to find out that no valid characters were received.


Please do not attribute these remarks to any other person or company.
                                   email: browns at iccgcc.decnet.ab.com
Stan Brown, Oak Road Systems, Cleveland, Ohio, USA    +1 216 371 0043



More information about the Comp.lang.c mailing list