如何在C中将字符串转换为整数? [英] How to convert a string to integer in C?
问题描述
我正在尝试找出在C中是否存在将字符串转换为整数的另一种方法.
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[] = "45";
int num = atoi(s);
那么,有没有更好的方法或另一种方法?
So, is there a better way or another way?
推荐答案
有 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.
这篇关于如何在C中将字符串转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!