【问题标题】:atoi() produces incorrect value when applied to a large command line argumentatoi() 应用于大型命令行参数时产生不正确的值
【发布时间】:2020-10-05 14:42:12
【问题描述】:

我从命令行读入值 300000000000 并使用 atoi 将其转换为 int64_t 但是它输出错误的值。

int main(int argc, char * const argv[]){
  int64_t timeSlice = -1;

  if(argc == 4){
      timeSlice = atoi(argv[1])
      cout<<"timeslice: "<<timeSlice<<endl;

  }
}

我在号码300000000000上运行我的程序

预期结果: timeSlice: 300000000000 实际输出: timeslice: -647710720 我什至尝试使用 stringstream 并且它会工作,但是当我将时间片传递给另一个函数时,该函数中的值仍然是错误的

【问题讨论】:

  • 你需要atol或环礁
  • atoi 是一个非常简单的工具。钝器。错误检查很少,因此在使用之前确保输入正确无误。
  • @Scheff,抱歉没有意识到。我会确保以后避免这样做

标签: c++ atoi int64


【解决方案1】:

这真的取决于您使用的是 32 位还是 64 位系统以及您使用的是 Windows 还是 Linux

atoi、atol、strtol 和 strtold 都将在 32 位可执行文件上返回一个 32 位数字。

atoll, strtoll 将在 32 位和 64 位可执行文件上返回一个 64 位数字

atol、strtol、strtold 将在 64 位 Windows 可执行文件上返回 32 位数字,但在 64 位 Linux 可执行文件上返回 64 位数字。

在 64 位 windows 可执行文件上,long=int,64 位 linux 可执行文件 long=long long

【讨论】:

  • 我通过 ssh 进入运行 linux 64 位系统的学校网络。
  • 您知道您是在构建 32 位还是 64 位可执行文件?
  • 它是一个 64 位的可执行文件
【解决方案2】:

使用strtoll函数:

timeSlice = strtoll(argv[1], nullptr, 10);

【讨论】:

  • timeSlice = strtoll(argv[1], nullptr, 10);有效,但是当我将 timeSlice 作为参数传递给另一个函数并将其打印出来时,它仍然给我相同的错误值-647710720
  • 您的打印效果如何?您使用的是 %d 还是 %ld 还是 %lld?
  • @DenisShevchenko 检查errno,而不是传入nullptr,而是传入char *,这样您就可以看到转换停止的位置。 Here's some documentation to help you out.
  • @user4581301,我更新了我的代码,现在它在我的 main 中打印出正确的值,但在 foo 中打印出相同的错误值。所以看起来它读对了,但传递错了。
  • 复制我不能。
猜你喜欢
  • 1970-01-01
  • 2011-11-12
  • 2021-02-21
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
  • 2011-06-30
相关资源
最近更新 更多