std::out_of_range error?
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
,开发者_如何学C 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?
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).
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.
Check that linelist_ptr
has a legitimate value, i.e. that you have new
ed it (and it hasn't been delete
d prior to you using it)
精彩评论