I made a code to check if a string is a palindrome. It works just fine for non-palindromes, but it outputs an error that goes along the line "terminate call after std::out_of_storage" when the inputted string is a palindrome. Here's the code.
Your include statement is non-standard C++, Not every compiler has it, don't use it. It is for internal use by the compiler only. Include <iostream> and <string> instead.
Erasing string elements is dangerous. If the checked string is a palindrome eventually the repeated recursion will erase from an empty string causing an exemption to be thrown.
There is no need to use recursion, iterating through a string is not that hard:
#include <iostream>
#include <string>
bool isPalindrome(std::string str)
{
size_t j {str.length() - 1 };
for (size_t i { }; i < j; i++, j--)
{
if (str[i] != str[j])
{
returnfalse;
}
}
returntrue;
}
int main()
{
std::string words[5] = { "mom", "radar", "level", "hello", "one" };
for (size_t i { }; i < 5; i++)
{
if (isPalindrome(words[i]))
{
std::cout << words[i] << " -> Palindrome\n";
}
else
{
std::cout << words[i] << " -> Not a Palindrome\n";
}
}
}
mom -> Palindrome
radar -> Palindrome
level -> Palindrome
hello -> Not a Palindrome
one -> Not a Palindrome
Something to consider, palindromes can be more than one word. "Madam, I'm Adam" is a classic example. Punctuation, spaces and capitalization of words needs to be dealt with when determining if a string is a palindrome.
The first argument to erase is the index position of the character that you want to remove.
You also forgot to always return something. My compiler says:
warning: control reaches end of non-void function
If you're using Clang or GCC you can enable this and many other useful warnings by using the -Wall compiler flag (you might also want to use -Wextra for even more warnings).
Okay thanks guys, all of your suggestions worked, i think my problem was the erase function (I didnt write the index, instead I wrote the character of the index)