gpt4 book ai didi

c - C语言中如何将字符串转换为整数?

转载 作者:行者123 更新时间:2023-11-30 17:07:58 24 4
gpt4 key购买 nike

我试图找出是否有其他方法可以在 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 berepresented, the behavior is undefined.

关于c - C语言中如何将字符串转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33930511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com