Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
把C++字符串转换成长,没有超出范围的异常_C++_String - Fatal编程技术网

把C++字符串转换成长,没有超出范围的异常

把C++字符串转换成长,没有超出范围的异常,c++,string,C++,String,我需要把一个带数字的字符串转换成长变量来做一些数学运算。 现在,我使用std::stol来实现它,但是当我插入一个太大的值时,该方法无法处理它,它会在参数超出范围时停止。 所以我的问题是:有没有一种方法可以在不耗尽内存的情况下转换long或long-long类型的字符串 这是我使用的代码: #include <iostream> int main() { std::string value = "95666426875"; long long converted_value =

我需要把一个带数字的字符串转换成长变量来做一些数学运算。 现在,我使用std::stol来实现它,但是当我插入一个太大的值时,该方法无法处理它,它会在参数超出范围时停止。 所以我的问题是:有没有一种方法可以在不耗尽内存的情况下转换long或long-long类型的字符串

这是我使用的代码:

#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;
}

在您的平台上,long似乎是32位宽的,因此95666426875太大,无法放入32位长的

使用解析为无符号long-long的stoull,而不是stoul。例如:

请注意,您不需要调用value.c_str。

您也可以使用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;
}

自己运行:

此外,从无符号long到long long的转换可能会丢失数据,因此变量也应该是无符号long long,或者应该调用stoll。但是,我觉得使用long-long可能是OP的一种有效解决方案,但我不能肯定。@chris添加了一个使用auto的示例。@MaximeGroushkin您的答案的问题是,我发布的代码中的示例值是一个用户输入变量,所以我不知道用户是否会插入一个更大的值..因为我尝试插入更大的值,但程序却以同样的错误停止了--即使是使用auto而不是unsigned long long我只是想每个软件都有一个输入限制,比如系统计算器,因此,我认为最好不要接受所有的值,并在输入太大时显示一条错误消息。感谢您提供这个解决方案@MaximeGroushkin@zDoes您是否可以捕获异常并向用户发出更具信息性的消息。当输入值太大而无法容纳时,您想做什么?
#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;
}