stoi 会导致超出范围的错误

stoi causes out of range error

本文关键字:范围 错误 stoi      更新时间:2023-10-16

我有这段代码,它给了我错误terminating with uncaught exception of type std::out_of_range: stoi: out of range

我已经确定是由线路引起的long ascii = std::stoi(temp_string);

我使用stoi导致这种情况的方式如何,我该如何解决它?

std::string encode(std::string message){
std::string num_value;
long cipher;
if(message.length() < 20){
  for(int i = 0; i < message.length(); ++i){
    int temp = (char) message.at(i); 
    num_value += std::to_string(temp); 
  }
  return num_value;
}
else{
    int count = 0;   
    std::string temp_string;
    for(int i = 0; i < message.length(); ++i){
      int temp = (int)  message.at(i);
      temp_string += std::to_string(temp);           
      count++;   
       if(count == 20){
         count = 0;
         //add cipher encrypt
         long ascii = std::stoi(temp_string);
         //cipher = pow(ascii, 10000);
         //add n to cipther encrypt
         //add cipherencrypt + n to num_value
         //reset temp_string
         temp_string += "n";
         temp_string = ""; 
      }
 }
return num_value;
}
int main(){
  std::string s = "Hello World my t's your name aaaaaaaaaaaaa?";
  std::cout<<"encoded value : "<< encode(s)<<std::endl;
}

std::stoi 返回一个整数;听起来你的数字对于整数来说太大了。尝试改用 std::stol (见这里)。

此外,如果您打算将代码移植(可用于不同的编译器/平台),请记住整数和长整型没有标准大小。除非标准给出的最小大小足够,否则您可能需要查看使用 intX_t(其中 X 是您想要的大小),如 cstdint 标头中给出的那样。