I have an algorithm which parses a string to test for a palindrome. Essentially what I want to do is see if the first and last characters of the string are equivalent. If this is the case, then I would want to remove the first and last characters of the string and pass that string to the function again in a recursive call.
Now I've run into a few issues with this code. First I think I'm preforming a bit of overkill here with all of the information I've prepared about the argument inString. I'm primarily pointing at the iterators. But I found that to use the more suitable overridden version of the erase method uses an iterator for single characters. But that really isn't the primary issue.
bool isPalindrome(string inString)
// variable declarations
char firstChar = inString.at(0); // the first character in the string
char lastChar = inString.at((int)inString.length()); // the last character in the string
int stringLength = (int)inString.length(); // the length of the string (num of chars)
string::iterator firstCharI = inString.begin(); // iterator beginning of the string
string::iterator lastCharI = inString.end(); // iterator ending of the string
if (inString == "" || stringLength == 1)
else if (firstChar == lastChar)
// hack off the first and last characters of the string
// recursive call to isPalindrome
The program that this method is coded into compiles fine however when I run the program, with the method above, I get an exception thrown std:ut_of_range which I'm guessing has to do with requested access to an element outside of array bounds, similar to a segmentation fault. Once I got that error, I modified this line in the isPalindrome method:
char lastChar = inString.at((int)inString.length());
The program compiled fine however execution terminated with a segmentation fault. I'm not exactly sure why I'm getting this error and I'm not exactly sure how to go about fixing it. If I could have some advice on clearing up this issue I'd appreciate it. Thanks in advance.
char lastChar = inString.at((int)inString.length() - 1);