How do I make sure that strtol() have returned successfully?

后端 未结 4 1185
天涯浪人
天涯浪人 2020-12-31 07:18

according documentation:

On success, the function returns the converted integral number as a long int value. If no valid conversion could be perfor

4条回答
  •  死守一世寂寞
    2020-12-31 07:21

    You need to pass a real pointer address if you want error checking, so you can distinguish 0 values arising from "0" and similar from 0 values arising from "pqr":

    char *endptr;
    errno = 0;
    long result = strtol(str, &endptr, 10);
    if (endptr == str)
    {
        // nothing parsed from the string, handle errors or exit
    }
    if ((result == LONG_MAX || result == LONG_MIN) && errno == ERANGE)
    {
        // out of range, handle or exit
    }
    // all went fine, go on
    

提交回复
热议问题