蒂()V / S。与strtol() [英] atol() v/s. strtol()
问题描述
什么是蒂()之间放大器的差异&;与strtol()?
What is the difference between atol() & strtol()?
据他们的人的页面,他们似乎有相同的效果以及与之相配套的参数:
According to their man pages, they seem to have the same effect as well as matching arguments:
long atol(const char *nptr);
long int strtol(const char *nptr, char **endptr, int base);
在一个广义的情况下,当我不想使用基
参数(我只是有小数),我应该使用哪些功能?
In a generalized case, when I don't want to use the base
argument (I just have decimal numbers), which function should I use?
推荐答案
与strtol
为您提供了更大的灵活性,因为它实际上可以告诉你,如果整个字符串转化为的整数或没有。 蒂
,当无法将字符串转换为数字(如在蒂(帮助)
),返回0 ,这是无法区分蒂(0)
:
strtol
provides you with more flexibility, as it can actually tell you if the whole string was converted to an integer or not. atol
, when unable to convert the string to a number (like in atol("help")
), returns 0, which is indistinguishable from 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
参数,其中的转换失败。
strtol
will specify, using its endptr
argument, where the conversion failed.
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
推荐使用。这是比较麻烦一些,使用,但这有一个很好的理由,正如我上面的解释。
Therefore, for any serious programming, I definitely recommend using strtol
. It's a bit more tricky to use but this has a good reason, as I explained above.
蒂
可能只适合于非常简单和控制的情况。
atol
may be suitable only for very simple and controlled cases.
这篇关于蒂()V / S。与strtol()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!