Out of range error on substr

Error: terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr: __pos (which is 2) > this->size() (which is 0)
Aborted (core dumped)

Seems to be focused in Employee.cpp on this line 'string sub = s.substr(2);'
I don't think the ranges are wrong so I think somethings wrong with the input. It takes a first set of numbers I specifically tried entering 'A 87000', it asks if i want to continue i pressed 'y' after which program crashes.

Any help is appreciated.

Last edited on
Try putting the cin.ignore() call after the cin>>goAhead call.
You most likely have a newline left in your cin buffer, causing the input string to be empty.

It's fragile code, though. I would suggest checking the length of input before you call push_back, to make sure it's at least 3 characters long.

PS: don't double post. Please delete your other thread.
Last edited on
See:

http://www.cplusplus.com/reference/string/string/substr/
If this is greater than the string length, it throws out_of_range.


stoi() will throw as well when the input is wrong. See:

http://www.cplusplus.com/reference/string/stoi/?kw=stoi


Lines 29/22/23 in Employee.cpp are all problematic when the input is wrong.

it asks if i want to continue i pressed 'y' after which program crashes.
The problem in thiat case is that line 20 in main.cpp leaves a newline in the stream. Line 16 will get this newline and provide an empty string to line 18. This will cause the exception.
Ganado -> Hey thanks for the tip, the ignore placement seems to have got me passed that error.

Ganado/Coder777 -> The length of the input should be okay as the dataset I have is consistent always one character, a space, and 5 numbers ex: 'A 87000'. Should have mentioned that.

Also sorry about double post, was unsure where was appropriate to post. Deleted the other one.
Last edited on
Topic archived. No new replies allowed.