Okay so first off, Im pretty new to programming, Ive only read a bit of stuff and have been working on some project Euler problems to kind of wrap my head around concepts and such. However, I got an error message today that I couldn’t make any sense of so I thought I would ask here for some help! Any links or advice is appreciated!
Here’s the error message:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr Aborted
So any advice you might have would be awesome! If you need to see my code or have questions, ask! Though I”d rather try to understand the problem then find the answer myself! Thanks!
EDIT: Okay since you guys say you would need to see the code here it is.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int stringtoint(string s_convertee)
{
int i=0;
istringstream sin(s_convertee);
sin >> i;
return i;
}
int main()
{
string s_testnum = "233456091289474545356";
int n_maxmult = 0;
for (int i = 0; i<s_testnum.length(); i++)
{
int n_product = 1;
for (int j = i; j<(i+4); j++)
{
string s_multiplier = s_testnum.substr(j, 1);
int n_multiplier = stringtoint(s_multiplier);
n_product *= n_multiplier;
}
if (n_product>n_maxmult)
{
n_maxmult = n_product;
}
}
return 0;
}
As other answers have already pointed out, in
substrIf the position passed is past the end of the string, an out_of_range exception is thrown.
In your code:
When
iis1less thans_testnum.length()jgoes pasts_testnum.length()and when you do,s_testnum.substr(j, 1);causes an out_of_range exception.