将C ++字符串转换为long而不会出现out_of_range异常

时间:2017-09-28 16:56:21

标签: c++ string

我需要将带有数字的字符串转换为long变量来进行一些数学运算 现在我使用std::stol来执行此操作,但是当我插入一个太大的值时,该方法无法处理它并且它会以argument out of range停止。
所以我的问题是:有没有办法在长(或长)类型中转换字符串而不会耗尽内存?

这是我使用的代码:

#include <iostream>

int main() {

std::string value = "95666426875";
long long converted_value = std::stoul(value.c_str());
//Some math calc here
std::cout << converted_value << std::endl;

return 0;

}

2 个答案:

答案 0 :(得分:2)

您的平台上的long看起来是32位宽,因此95666426875太大而无法容纳32位long

使用stoull解析为unsigned long long,而不是stoul。 E.g:

auto converted_value = std::stoull(value);

(请注意,您无需致电value.c_str())。

答案 1 :(得分:0)

您也可以使用stringstream

#include <iostream>
#include <sstream>

int main ()
{
  std::string value = "95666426875";

  //number which will contain the result
  unsigned long long Result;

  // stringstream used for the conversion initialized with the contents of value
  std::stringstream ss_value (value);

  //convert into the actual type here
  if (!(ss_value >> Result))
    {
      //if that fails set Result to 0
      Result = 0;
    }

  std::cout << Result;

  return 0;
}

自己运行:link