strtol
为您提供了更大的灵活性,因为它实际上可以告诉您整个字符串是否已转换为整数。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;
}
Outputs:
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;
}
Outputs:
Conversion error, non-convertible part: help
因此,对于任何严肃的编程,我绝对建议使用strtol
。使用起来有点棘手,但这是有充分理由的,正如我上面所解释的。
atol
可能仅适用于非常简单且受控的情况。