且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C中将字符串转换为整数?

更新时间:2023-02-03 08:34:00

strtol ,这是更好的IMO.我也很喜欢 strtonum ,因此请使用它(但请记住它不是便携式的):

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);

您可能还对 strtoumax strtoimax 是C99中的标准功能.例如,您可以说:

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. */

无论如何,请远离 atoi :

调用atoi(str)应等效于:

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.