Hi Guys,
I am trying to create a simple palindrome program.
I get the error string subscript out of range.
I am learning c++ on my own and have spent many hours trying to figure out what is wrong. Help is most appreciated. Thanks!
I believe the error is either in the while or for loops.
What output causes the error ?
For all the outputs i gave , i just got <input> is not a palindrome.
If I may suggest a little modification to the funtion cleanTolower()
1 2 3 4 5 6 7
bool isPalindrome(const string& s) //changed the name , cleanTolower is misleading
{
for(std::size_t i = 0 , j = s.size() - 1; i < j ; ++i,--j)
if(tolower(s[i]) != tolower(s[j]))
returnfalse;//if the corresponding characters are not same quit early.
returntrue;//if we made it through the loop it's a palindrome.
}
The above code is much smaller (and easier to read .)
Further if you want to check if a line containing white-spaces is palindrome(spaces , tabs ..) , you can first the copy the string s , and remove all the spaces from it.Like this ,
1 2 3 4 5 6 7 8
std::string copy = s;
for(auto it = copy.begin(); it != copy.end() ;)
{
if(iswspace(*it))
it = copy.erase(it);
else
++it;
}
you can add this code to the isPalindrome() function above (and replace 's' with 'copy' in the loop).
string::size_type end = cleanString.size();
bool isPal;
while (start < end)
{
if (cleanString[start] == cleanString[end])
{
isPal = true;
start++, end--;
}
else
isPal = false;
}
Remember that in C++, container indices start at 0, not 1. So in the first iteration of that while loop, cleanString[end] is past the end of the string.