C++ stoi导致超出范围错误

C++ stoi导致超出范围错误,c++,outofrangeexception,C++,Outofrangeexception,我有一个代码,它给出了一个错误,以std::out_of_range:stoi:out of range类型的未捕获异常终止 我已经确定这是由行long ascii=std::stoi(temp_字符串)引起的 我使用stoi的方式会导致这种情况吗?我该如何修复它 std::string encode(std::string message){ std::string num_value; long cipher; if(message.length() < 20){ for(int

我有一个代码,它给出了一个错误
,以std::out_of_range:stoi:out of range类型的未捕获异常终止

我已经确定这是由行
long ascii=std::stoi(temp_字符串)引起的

我使用
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::string编码(std::string消息){
std::字符串num_值;
长密码;
if(message.length()<20){
对于(int i=0;istd::coutstd::stoi返回一个整数;听起来您的数字对于整数来说太大了。请尝试改用std::stol(请参阅)


此外,如果您希望代码具有可移植性(可用于不同的编译器/平台),请记住整数和long没有标准大小。除非给定的最小大小足够,否则您可能需要考虑使用intX\u t(其中X是您想要的大小),如cstdint标题中所示。

您是否尝试打印
temp_字符串
,以查看它是否在
int
的范围内?对于您的异常有一些见解:“如果转换的值将超出结果类型的范围,或者如果基础函数(std::strtol或std::strtoll)不在范围内,则std::out_of_”将errno设置为ERANGE。“什么是
temp_string=“”
应该做什么?请问您的最小测试用例在哪里?您甚至没有告诉我们您的输入是什么!!!只是将数字的文本表示形式附加在一起以生成一个更大的数字?您失去了边界,现在979可能是9,79或97,9(这两种都是有效的且并非异常的ASCII序列)
stol
确实与结果存储到的变量更为一致,但这可能还不够大。这是一个公平的观点;我假设长声明意味着输入受到约束,但我在代码中没有看到任何此类约束。除了移动到任意大小的库之外,我不确定还有什么建议。@BenVoigt程序的上下文是rsa加密,我选择的加密路线是以20个字符的块获得ascii值,并将每个块传递到
c=pow(m,e)中mod n
formula。我正在尝试将块保存在一个临时字符串变量中,将其转换为一个数字,放入公式中,然后对块的数量进行重复。@ralphie9224:在RSA加密中,任何一步都不应该使用十进制数字。使用位移可以很容易地将20个字符连接成一个大的数字,但需要160位数据类型,我不认为C++编译器有。什么数据类型是你的代码> POW(M,E)mod n</代码>函数?我使用GMP库来生成足够大的数字,所以传递给它的值将超过长度或int长度。