Using strtol to validate integer input in ANSI C

前端 未结 3 2159
梦如初夏
梦如初夏 2021-01-14 07:23

I am new to programming and to C in general and am currently studying it at university. This is for an assignment so I would like to avoid direct answers but are more after

相关标签:
3条回答
  • 2021-01-14 07:44

    You're checking the outcome of strtol in the wrong order, check ptr first, also don't check ptr against NULL, derference it and check that it points to the NUL ('\0') string terminator.

    if (*ptr == '\0') {
      // this means all characters were parsed and converted to `long`
    }
    else {
      // this means either no characters were parsed correctly in which
      // case the return value is completely invalid
      // or
      // there was a partial parsing of a number to `long` which is returned
      // and ptr points to the remaining string
    }
    

    num > 1000001 also needs to be num > 1000000

    num < 0 also needs to be num < 1

    You can also with some reorganising and logic tweaks collapse your sequence of if statements down to only a single invalid branch and a okay branch.

    0 讨论(0)
  • 2021-01-14 07:57

    The function strtol returns long int, which is a signed value. I suggest that you use another variable (entry_num), which you could test for <0, thus detecting negative numbers.

    I would also suggest that regex could test string input for digits and valid input, or you could use strtok and anything but digits as the delimiter ;-) Or you could scan the input string using validation, something like:

    int validate_input ( char* input )
    {
        char *p = input;
        if( !input ) return 0;
        for( p=input; *p && (isdigit(*p) || iswhite(*p)); ++p )
        {
        }
        if( *p ) return 0;
        return 1;
    }
    
    0 讨论(0)
  • 2021-01-14 08:01

    OP would like to avoid direct answers ....

    validate integer input

    1. Separate I/O from validation - 2 different functions.

    2. I/O: Assume hostile input. (Text, too much text, too little text. I/O errors.) Do you want to consume leading spaces as part of I/O? Do you want to consume leading 0 as part of I/O? (suggest not)

    3. Validate the string (NULL, lead space OK?, digits after a trailing space, too short, too long, under-range, over-range, Is 123.0 an OK integer)

    4. strtol() is your friend to do the heavy conversion lifting. Check how errno should be set and tested afterward. Use the endptr. Should its value be set before. How to test afterward. It consume leading spaces, is that OK? It converts text to a long, but OP wants the nebulous "integer".

    Qapla'

    0 讨论(0)
提交回复
热议问题