c - atol() 与 strtol()

标签 c strtol

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

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

long atol(const char *nptr);

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

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

最佳答案

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

关于c - atol() 与 strtol(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3792663/

相关文章:

c - 标量初始值设定项中的元素过多,我在 C 中不断遇到错误

c - 在 GBDK C 项目中包含静态库 (GBExtended)

c - 手动将协议(protocol)头与正文分离

c - 下载头文件

c - strtol c 字符串函数

c - 使用 strtol() 解析文件行中的长值

c - 是否有 C 函数来获取文件的权限?

c++ - atoi 中的 null 将值转换为 0

c - strtol 不从读取(fd、缓冲区、ssize_t)转换字符串

c - 如何让这个程序可以接受负数