Hello,
This kinda has to do with a function I am making for a homework assignment but it is one that I'm making. I really want to figure it out but just need a little help. I made a while loop to look for "=" signs in a string and to count how many there are. I got the while loop to do what I ask but when I run the code it says aborted at the end and it ends the entire program. Any help on why it is aborting and a direction on what I can do to stop it is greatly appreciated, I spent a lot of time trying everything I can think of.
The problem arises when your substring no longer contains any "=". myString.find will then return std::string::npos, which is a position that shouldn't exist in the string (it is usually the maximum value of size_t, which is much larger than any normal string would possibly be).
Next you pass this value to substr, which expects to get a valid index. It gets an invalid index however, and will try to create a substring from someplace not in your string, and throw an out_of_range exception. You do not handle this exception, causing the crash.
The easiest way to change this, is to make sure you get a valid index every time you execute your loop. The easiest way I can think up would be:
I would probably declare spot and pos as std::string::size_type instead of as int. This way you know that the actual positions will always fit in the variable. As you can see I also removed all irrelevant code from the actual function, including the call to substring, since it wasn't required at all. You can thrust std::string::find to really find your string, taking a substring to check it again will not make any difference.
HI jlb,
Thanks, I edited my message so it contains entire program. I'm trying to count how many equal signs there are in a string and update the "count" integer. when I take out the equal signs the program just shows aborted. and myString.find() sends back a -1. Thanks for your help.
The fact that you're seeing a -1 is because of signed to unsigned conversion. std::string::size_type (the actual type string.find returns) is an unsigned type. It returns the value std::string::npos when it cannot find the value, which is the maximum value it can take. When converting it to signed, it will be converted to -1 (although this isn't a guarantee, casing an unsigned int to a signed int out of the bounds of the signed int is undefined behavior, so anything could happen, from crashes to demons appearing, from signed to unsigned is defined though).
I already posted the solution around half an hour ago. Just read the post, I know it's long.