stoi导致超出范围的错误 [英] stoi causes out of range error

查看:923
本文介绍了stoi导致超出范围的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this code which gives me the error terminating with uncaught exception of type std::out_of_range: stoi: out of range

是由long ascii = std::stoi(temp_string);

导致我使用stoi的方式是什么,我该如何解决?

what about the way i'm using stoi is causing that and how can I fix it?

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(请参见此处).

std::stoi returns an integer; it sounds like your number is too large for an integer. Try using std::stol instead (see here).

此外,如果您打算使代码具有可移植性(可与不同的编译器/平台一起使用),请记住,整数和long没有标准大小.除非标准给出的最小大小足够,否则您可能要考虑使用intX_t(其中X是您想要的大小),如cstdint标头中所述.

Also if you intend for the code to be portable (useable with different compilers/platforms), keep in mind that integers and longs have no standard size. Unless the minimum size given by the standard is enough, you may want to look at using intX_t (where X is the size you want), as given in the cstdint header.

这篇关于stoi导致超出范围的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆