Stoi raises out of range error
I have this code which is giving me error terminating with uncaught exception of type std::out_of_range: stoi: out of range
which I identified as being caused by the line long ascii = std::stoi(temp_string);
what about how i am using stoi
causes this and how to 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 your name aaaaaaaaaaaaa?";
std::cout<<"encoded value : "<< encode(s)<<std::endl;
}
source to share
std :: stoi returns an integer; it looks like your number is too big for an integer. Try using std :: stol instead (see here ).
Also, if you intend to use portable code (can be used with different compilers / platforms), keep in mind that integers and longs do not have a standard size. If the minimum size is given by the standard , you might need to use intX_t (where X is the size you want) as stated in the cstdint header.
source to share