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

时间:2011-06-01 15:21:24

标签: c++ string

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

以下是错误消息:

terminate called after throwing an instance of 'std::out_of_range'  
what(): basic_string::substr Aborted

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

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

#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;
}

6 个答案:

答案 0 :(得分:5)

来自C++ Reference for substr

  

如果通过的位置超过了结束   字符串,out_of_range   抛出异常。

所以我猜你的调用substr的第一个参数大于字符串长度。


由于您已发布代码,因此可以看到

i最多可以是s_testnum.length()-1

但是

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

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

答案 1 :(得分:3)

请发布有问题的代码。你有可能做过这样的事情:

std::string s("foo");
s.substr(5, 1); // The length of the string is 3, 5 is out of bounds

答案 2 :(得分:3)

正如其他答案已经指出的那样,在substr

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

在您的代码中:

for (int j = i; j<(i+4); j++)

i 1小于s_testnum.length() j超过s_testnum.length()时,s_testnum.substr(j, 1);会导致 out_of_range 例外。

答案 3 :(得分:2)

您调用代码中某些字符串的substr函数的参数很可能超过了字符串长度。因此std::out_of_range例外。但是如果不看代码就很难说。此外,您可以使用调试器(如gdb / ddd)逐步执行代码并自行调试。只需确保在g ++上使用-g标志编译代码。

答案 4 :(得分:2)

你用无效参数调用substr - 你正在尝试获取字符串的元素,而不是那里 - 例如当字符串只有5时尝试获取第10个字符。

在你的情况下,这是由substr引起的 - 你试图获得一个子字符串,这对于指向的起始位置来说太长了并且它“超出”了真正的字符串。


terminate called after throwing an instance of 'std::out_of_range'

^^^^说,你有一个未捕获的异常,即out_of_range

what(): basic_string::substr Aborted

^^^^这是例外文本 - 注意substr

答案 5 :(得分:0)

您应该能够安排调试器在抛出异常时中断。在调试器下运行程序,设置适当的断点,然后查看堆栈回溯。 (对于记录,Ctrl + Alt + E应显示一个对话框,其中包含Visual Studio中的异常处理选项;命令catch throw激活gdb下的异常断点。)