atol()和strtol()有什么区别?
根据他们的手册页,它们似乎具有相同的效果以及匹配的论点:
long atol(const char *nptr);
long int strtol(const char *nptr, char **endptr, int base);在一般情况下,当我不想使用base参数(我只有十进制数)时,我应该使用哪个函数?
发布于 2010-09-25 13:54:58
strtol为您提供了更大的灵活性,因为它实际上可以告诉您整个字符串是否已转换为整数。当无法将字符串转换为数字时(如在atol("help")中),atol将返回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: 0strtol将使用其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可能只适用于非常简单和可控的情况。
发布于 2010-09-25 13:57:09
atol功能是strtol功能的一个子集,只是atol没有提供可用的错误处理功能。ato...函数最突出的问题是,在发生溢出时,它们会导致未定义的行为。注意:这不仅仅是在错误的情况下缺乏信息反馈,这是一种未定义的行为,即通常是不可恢复的故障。
这意味着atol函数(以及所有其他ato..函数)对于任何严肃的实际目的都几乎没有用处。这是一个设计上的错误,它的位置在C语言历史的垃圾场上。您应该使用strto...组中的函数来执行转换。它们的引入,尤其是为了纠正ato...组的功能中固有的问题。
发布于 2012-11-08 13:34:55
根据strtol的atoi手册页,它已被弃用。
IMPLEMENTATION NOTES
The atoi() and atoi_l() functions have been deprecated by strtol() and strtol_l()
and should not be used in new code.https://stackoverflow.com/questions/3792663
复制相似问题