0

我正在处理一个带有行链表的文件,每个节点看起来像这样:

struct TextLine{
    //The actual text
    string text;
    //The line number of the document
    int line_num;
    //A pointer to the next line
    TextLine * next;
};

text我正在编写一个函数,通过调用如下函数在变量中找到的行的开头添加空格linelist_ptr->text.insert(0,1,'\t');

该程序可以编译,但是当我运行它时,出现此错误:

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

有任何想法吗?

4

3 回答 3

1

您在代码中的某处使用了 std::string::at() 但您传递给它的索引不正确,因此它会抛出。由于您没有捕获任何异常,因此它从 main() 传播并调用了 terminate(),从而终止了该进程。

您显示的代码不会以这种方式失败,因为 std::string::insert() 不会调用 std::string::at(),参数也不会。请在您的代码中添加异常处理,如果您仍然无法找到错误,请发布您的代码的较大部分(或整个文件,最好发布到http://codepad.org)。

于 2010-05-27T03:40:32.830 回答
1

我认为您所描述的最可能的问题是insert() 被调用时使用了字符串末尾的无效位置(即> size())。你说这个例子就像你正在调用的函数,所以检查你可能写的那些你可能传递位置的地方与上面的示例代码不同,并确保值是你期望的。

终止消息是因为您没有处理out_of_range异常(通过 try/catch 块),因此它会逃到 C++ 语言运行时,这会毫不客气地关闭您的程序。

于 2010-05-27T06:52:45.793 回答
0

检查它linelist_ptr是否具有合法价值,即您已编辑它(并且在您使用它之前new没有被d)delete

于 2010-05-27T03:40:10.240 回答