Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stoi causes out of range error

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

which I have identified as being caused by the line long ascii = std::stoi(temp_string);

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;
}
like image 283
Rafa Avatar asked Apr 28 '15 23:04

Rafa


People also ask

What is range of stoi in C++?

The set of valid values for base is {0,2,3,...,36}. The set of valid digits for base- 2 integers is {0,1}, for base- 3 integers is {0,1,2}, and so on.

What can I use instead of stoi in C++?

As you can see, we still declare the str1 to be 123, but then we have to use stringstream instead of stoi. stringstream allows us to place str1 into an object that, in this example, is named container.

What does stoi return if fails?

If no conversion could be performed, zero is returned. The previous reference said that no conversion would be performed, so it must return 0. These conditions now comply with the C++11 standard for stoi throwing std::invalid_argument .

Does stoi ignore whitespace?

stoistolstoll Interprets a signed integer value in the string str . Function discards any whitespace characters (as identified by calling isspace() ) until first non-whitespace character is found.


1 Answers

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

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.

like image 103
sabreitweiser Avatar answered Sep 30 '22 17:09

sabreitweiser