std::out_of_range 错误?
我正在处理一个带有行链接列表的文件,每个节点如下所示:
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
有什么想法吗?
I'm dealing with a file with a linked list of lines with each node looking like this:
struct TextLine{
//The actual text
string text;
//The line number of the document
int line_num;
//A pointer to the next line
TextLine * next;
};
and I'm writing a function that adds spaces at the beginning of the lines found in the variable text
, by calling functions like linelist_ptr->text.insert(0,1,'\t');
The program compiles, but when I run it I get this error:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at
Aborted
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在代码中的某处使用了 std::string::at() 但您向它传递了不正确的索引,因此它会抛出。由于您没有捕获任何异常,因此它会从 main() 传播出去并调用 Terminate() ,从而终止该进程。
您显示的代码不会以这种方式失败,因为 std::string::insert() 不会调用 std::string::at(),参数也不会。请在您的代码中添加异常处理,如果您仍然找不到错误,请将代码的较大部分(或整个文件)发布到 http://codepad.org 最好)。
You are using the std::string::at() somewhere in your code but you are passing it an incorrect index, hence it throws. Since you don't catch any exceptions it propagates out of main() and terminate() is called, killing the process.
The code you've shown can't fail in that way, as std::string::insert() doesn't call std::string::at(), nor are the parameters. Please add exception handling to your code and if you still can't find the bug please post a larger section of your code (or the whole file, to http://codepad.org preferably).
我认为您所描述的最可能的问题是调用 insert() 时使用了字符串末尾的无效位置(即 > size())。您说这个示例像您正在调用的函数,因此请检查您可能编写的可能与上面示例代码不同的传递位置的示例,并确保该值是您期望的值。
终止消息是因为您没有处理
out_of_range
异常(通过 try/catch 块),因此它会转义到 C++ 语言运行时,从而毫不客气地关闭您的程序。I think the most likely problem from what you've described is that insert() is being invoked with an invalid position off the end of the string (i.e. > size()). You say this example is like the functions you're calling, so check the ones you may have written where you might be passing position differently than the sample code above and make sure the value is what you expect.
The terminate message is because you're not handling the
out_of_range
exception (via try/catch blocks), so it escapes up to the C++ language runtime, which unceremoniously shuts your program down.检查
linelist_ptr
是否具有合法值,即您已对其进行new
编辑(并且在使用它之前尚未删除
) )Check that
linelist_ptr
has a legitimate value, i.e. that you havenew
ed it (and it hasn't beendelete
d prior to you using it)