atol()v/s.与strtol()

60 c strtol

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

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

long atol(const char *nptr);

long int strtol(const char *nptr, char **endptr, int base);
Run Code Online (Sandbox Code Playgroud)

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

Eli*_*sky 85

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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Got from help: 0, from zero: 0
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Conversion error, non-convertible part: help
Run Code Online (Sandbox Code Playgroud)

因此,对于任何严肃的编程,我绝对建议使用strtol.使用它有点棘手,但这有一个很好的理由,正如我上面所解释的那样.

atol 可能仅适用于非常简单和受控的情况.

  • 这不会处理与超出范围的数字相关的错误.为此,需要检查错误! (4认同)
  • 我相信你的例子,条件应该是`if(!*end)`.它将指向字符串的null终止符(如果它已全部转换)但不会自己设置为NULL. (3认同)

AnT*_*AnT 20

atol功能是功能的子集strtol,除了atol为您提供无可用的错误处理功能.ato...函数最突出的问题是它们会在溢出时导致未定义的行为.注意:这不仅仅是在出现错误时缺乏信息反馈,这是未定义的行为,即通常是不可恢复的失败.

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


jfm*_*cer 18

根据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.
Run Code Online (Sandbox Code Playgroud)


sch*_*hot 6

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

C99 标准规定了这些ato*功能:

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

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


And*_*ein 5

atol(str) 相当于

strtol(str, (char **)NULL, 10);
Run Code Online (Sandbox Code Playgroud)

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