atoi vs atol vs strtol vs strtoul vs sscanf

后端 未结 2 1904
情歌与酒
情歌与酒 2020-11-29 22:47

I\'m trying to figure out from a command line being parsed, which function would be best to convert either a decimal, hexadecimal, or octal number to an int the

2条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 23:19

    It is only sensible to consider strtol() and strtoul() (or strtoll() or strtoull() from , or perhaps strtoimax() or strtoumax() from ) if you care about error conditions. If you don't care about error conditions on overflow, any of them could be used. Neither atoi() nor atol() nor sscanf() gives you control if the values overflow. Additionally, neither atoi() nor atol() provides support for hex or octal inputs (so in fact you can't use those to meet your requirements).

    Note that calling the strtoX() functions is not entirely trivial. You have to set errno to 0 before calling them, and pass a pointer to get the end location, and analyze carefully to know what happened. Remember, all possible return values from these functions are valid outputs, but some of them may also indicate invalid inputs — and errno and the end pointer help you distinguish between them all.

    If you need to convert to int after reading the value using, say, strtoll(), you can check the range of the returned value (stored in a long long) against the range defined in for int: INT_MIN and INT_MAX.

    For full details, see my answer at: Correct usage of strtol().

    Note that none of these functions tells you which conversion was used. You'll need to analyze the string yourself. Quirky note: did you know that there is no decimal 0 in C source; when you write 0, you are writing an octal constant (because its first digit is a 0). There are no practical consequences to this piece of trivia.

提交回复
热议问题