我试图找出是否有其他方法可以在 C 中将字符串转换为整数。
我经常在我的代码中构建以下模式。
char s[] = "45";
int num = atoi(s);
那么,有没有更好的方法或其他方法?
最佳答案
有strtol
IMO 哪个更好。我也喜欢strtonum
,所以如果你有的话就使用它(但记住它不可移植):
long long
strtonum(const char *nptr, long long minval, long long maxval,
const char **errstr);
您可能还对 strtoumax
and strtoimax
感兴趣这是C99中的标准函数。例如你可以说:
uintmax_t num = strtoumax(s, NULL, 10);
if (num == UINTMAX_MAX && errno == ERANGE)
/* Could not convert. */
无论如何,远离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.
关于c - C语言中如何将字符串转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56685269/