Using strtol to validate integer input in ANSI C

前端 未结 3 2153
梦如初夏
梦如初夏 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.

提交回复
热议问题