我尝试运行程序时出现C++ std :: out_of_range错误

sam*_*oul 1 c++ string

好吧,首先,我是一个很新的编程,我只阅读了一些东西,并一直致力于一些项目欧拉问题,以包括我的头围绕概念等.但是,我今天收到一条错误消息,我无法理解,所以我想我会在这里寻求帮助!任何链接或建议表示赞赏!

这是错误消息:

terminate called after throwing an instance of 'std::out_of_range'  
what(): basic_string::substr Aborted
Run Code Online (Sandbox Code Playgroud)

所以你可能有的任何建议都会很棒!如果您需要查看我的代码或有疑问,请询问!虽然我宁愿尝试理解问题,但我自己也找到了答案!谢谢!

编辑:好的,因为你们说你需要在这里查看代码.

#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;
}
Run Code Online (Sandbox Code Playgroud)

tjm*_*tjm 5

来自substr的C++参考,

如果传递的位置超过字符串的结尾,则抛出out_of_range异常.

所以我的猜测是你substr的第一个参数大于字符串长度.


既然你发布了代码,你可以看到,

i可以是最大的s_testnum.length()-1,

j上升i+4-1= s_testnum.length()+2.

然后substr使用第一个参数调用,j其中所述参数可以长于字符串长度.所以有问题.