How to convert a string to integer in C?

后端 未结 12 1551
清酒与你
清酒与你 2020-11-22 01:40

I am trying to find out if there is an alternative way of converting string to integer in C.

I regularly pattern the following in my code.

char s[] =         


        
12条回答
  •  抹茶落季
    2020-11-22 02:03

    There is strtol which is better IMO. Also I have taken a liking in strtonum, so use it if you have it (but remember it's not portable):

    long long
         strtonum(const char *nptr, long long minval, long long maxval,
         const char **errstr);
    

    EDIT

    You might also be interested in strtoumax and strtoimax which are standard functions in C99. For example you could say:

    uintmax_t num = strtoumax(s, NULL, 10);
    if (num == UINTMAX_MAX && errno == ERANGE)
        /* Could not convert. */
    

    Anyway, stay away from atoi:

    The call atoi(str) shall be equivalent to:

    (int) strtol(str, (char **)NULL, 10)
    

    except that the handling of errors may differ. If the value cannot be represented, the behavior is undefined.

提交回复
热议问题