gpt4 book ai didi

c - atol() 与 strtol()

转载 作者:太空狗 更新时间:2023-10-29 16:17:11 31 4
gpt4 key购买 nike

atol() 和 strtol() 有什么区别?

根据他们的手册页,它们似乎具有相同的效果以及匹配的参数:

long atol(const char *nptr);

long int strtol(const char *nptr, char **endptr, int base);

在一般情况下,当我不想使用 base 参数(我只有十进制数)时,我应该使用哪个函数?

最佳答案

strtol 为您提供了更大的灵 active ,因为它实际上可以告诉您整个字符串是否已转换为整数。 atol,当无法将字符串转换为数字时(如atol("help")),返回0,这与atol("0 "):

int main()
{
int res_help = atol("help");
int res_zero = atol("0");

printf("Got from help: %d, from zero: %d\n", res_help, res_zero);
return 0;
}

输出:

Got from help: 0, from zero: 0

strtol 将使用其 endptr 参数指定转换失败的位置。

int main()
{
char* end;
int res_help = strtol("help", &end, 10);

if (!*end)
printf("Converted successfully\n");
else
printf("Conversion error, non-convertible part: %s", end);

return 0;
}

输出:

Conversion error, non-convertible part: help

因此,对于任何严肃的编程,我绝对推荐使用strtol。使用起来有点棘手,但这是有充分理由的,正如我在上面解释的那样。

atol 可能只适用于非常简单和受控的情况。

关于c - atol() 与 strtol(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3792663/

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