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

标签 c string atoi

我试图找出是否有其他方法可以在 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/

相关文章:

iphone - 调用[[super allocWithZone :nil] init],消息机制

C : Splint pointers related warnings. 它们是什么意思?

c++ - 为什么我的字符串的开头消失了?

c - 如何在c中将2D char数组转换为2D int

c - 如何通过 gcc 临时文件创建进行故障排除

c - 全局变量是否被视为语句?

java - 将字符数组转换为不带空格的字符串

java - 如何在java中打印字符串中的重复字符

c - atoi 沮丧

assembly - NASM程序集将输入转换为整数?