I have this code which gives me the error terminating with uncaught exception of type std::out_of_range: stoi: out of range
我有这个代码,它给我错误终止与类型std :: out_of_range的未捕获异常:stoi:超出范围
which I have identified as being caused by the line long ascii = std::stoi(temp_string);
我已经确定是由长行ascii = std :: stoi(temp_string)引起的;
what about the way i'm using stoi
is causing that and how can I fix it?
我正在使用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;
}
1 个解决方案
#1
3
std::stoi returns an integer; it sounds like your number is too large for an integer. Try using std::stol instead (see here).
std :: stoi返回一个整数;听起来你的数字对于一个整数来说太大了。尝试使用std :: stol(参见此处)。
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.
此外,如果您打算使代码可移植(可与不同的编译器/平台一起使用),请记住整数和长整数没有标准大小。除非标准给出的最小大小足够,否则您可能需要查看使用intX_t(其中X是您想要的大小),如cstdint标头中所示。
#1
3
std::stoi returns an integer; it sounds like your number is too large for an integer. Try using std::stol instead (see here).
std :: stoi返回一个整数;听起来你的数字对于一个整数来说太大了。尝试使用std :: stol(参见此处)。
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.
此外,如果您打算使代码可移植(可与不同的编译器/平台一起使用),请记住整数和长整数没有标准大小。除非标准给出的最小大小足够,否则您可能需要查看使用intX_t(其中X是您想要的大小),如cstdint标头中所示。