是什么蒂之间()strtol将差&()?

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

long atol(const char *nptr);

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

在广义的情况下,当我不想使用base参数(我只是有小数),我应该用哪个函数?

有帮助吗?

解决方案

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;
}

输出:

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可能只适合非常简单的和受控的情况下。

其他提示

atol功能的strtol功能的子集,不同之处在于atol提供了没有可用的错误处理功能。与ato...功能最突出的问题是,它们会导致未定义行为溢出的情况。注意:这不仅仅是缺乏在发生错误的情况下的信息反馈,这是未定义的行为,即通常无法恢复的故障

这意味着atol功能(以及所有其他ato..函数)为任何严重的实际目的几乎无用。这是一个设计错误,取而代之的是基于C历史的垃圾堆。您应该使用功能从strto...组来执行转换。他们进行了介绍,除其他事项外,为了校正在ato...功能组所固有的问题。

按照atoi手册页,它已被strtol弃用。

IMPLEMENTATION NOTES
The atoi() and atoi_l() functions have been deprecated by strtol() and strtol_l() 
and should not be used in new code.

在新的代码我将总是使用strtol。它有错误处理和endptr参数允许你看到其中使用字符串的一部分。

关于ato*函数C99标准状态:

除了在错误的行为,它们相当于

atoi: (int)strtol(nptr,(char **)NULL, 10)结果 atol: strtol(nptr,(char **)NULL, 10)结果 atoll: strtoll(nptr, (char **)NULL, 10)

atol(str)相当于

strtol(str, (char **)NULL, 10);

如果要结束指针(以检查是否有更多的字符要读取或如果事实上已阅读任何的话)使用与strtol或大于10以外的碱基否则,蒂是好的。

如果记错,strtol()具有额外的好处(可选的)endptr至点设定为第一字符不能被转换。如果NULL,它将被忽略。这样,如果你正在处理包含数字和字符的字符串混合,你可能会继续下去。

如,

char buf[] = "213982 and the rest";
char *theRest;
long int num = strtol(buf, &theRest, 10);
printf("%ld\n", num);    /* 213982 */
printf("%s\n", theRest); /* " and the rest" */

strtol将所述的人页给出了以下情况:

ERRORS
   EINVAL (not in C99) The given base contains an unsupported value.
   ERANGE The resulting value was out of range.
   The implementation may also set errno to EINVAL in case no conversion was performed (no digits seen, and 0 returned).

下面的代码检查范围的错误。 (变形以利的码位)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int main()
{
   errno = 0;
   char* end = 0;
   long res = strtol("83459299999999999K997", &end, 10);

   if(errno != 0)
   {
      printf("Conversion error, %s\n", strerror(errno));
   }
   else if (*end)
   {
      printf("Converted partially: %i, non-convertible part: %s\n", res, end);
   }
   else
   {
      printf("Converted successfully: %i\n", res);
   }

   return 0;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top