68

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

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

long atol(const char *nptr);

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

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

4

7 回答 7

98

strtol为您提供了更大的灵活性,因为它实际上可以告诉您整个字符串是否已转换为整数。atol,当无法将字符串转换为数字时(如 in 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可能只适用于非常简单和受控的情况。

于 2010-09-25T05:54:57.990 回答
22

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

这意味着atol函数(以及所有其他ato..函数)对于任何严肃的实际目的都几乎没有用处。这是一个设计错误,它的位置是 C 历史的垃圾场。您应该使用strto...组中的函数来执行转换。除其他外,它们的引入是为了纠正ato...群体功能中固有的问题。

于 2010-09-25T05:57:09.117 回答
19

根据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.
于 2012-11-08T05:34:54.537 回答
5

atol(str)相当于

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

如果您想要结束指针(检查是否有更多字符要读取,或者实际上您是否已经读取任何字符)或不是 10 的基数,请使用 strtol。否则,atol 很好。

于 2010-09-25T05:55:48.980 回答
4

在新代码中,我总是使用strtol. 它具有错误处理功能,并且该endptr参数允许您查看使用了字符串的哪一部分。

C99 标准规定了以下ato*功能:

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

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

于 2010-09-25T05:55:42.373 回答
2

如果没记错的话,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" */
于 2010-09-25T05:56:08.423 回答
1

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).

以下代码检查范围错误。(稍微修改了 Eli 的代码)

#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;
}
于 2012-12-05T17:41:13.943 回答