I am trying to finish my program and it keeps saying that it is a Palindrome or it is not all the time when I tweak my code. I believe the problem is in the function if else statement but I cant seem to make it right. Here is what I have.
#include <iostream>
#include<string>
using namespace std;
bool recursionPalindrome(string mString, int start, int end);
int main()
{
string Pstring;
char choice;
do
{
cout << "Type a sentence/word and I will determine if it is a Palindrome or not." << endl;
getline(cin, Pstring);
int last = Pstring.length();
if (recursionPalindrome(Pstring, 0, last))
cout << "It is a Palindrome" << endl;
else
cout << "It is not a palindrome" << endl;
cout << "\nWould you like to test another for a Palindrome? ";
cin >> choice;
cin.ignore();
} while (choice == 'Y' || choice == 'y');
cout << endl;
return 0;
}
bool recursionPalindrome(string mString, int start, int end)
{
if (mString[end] == '\0')
return true;
else
if (mString[start] == mString[end])
return recursionPalindrome(mString, start + 1, end - 1);
#include <iostream>
#include <string>
usingnamespace std;
bool recursionPalindrome(string mString, int start, int end);
int main()
{
string Pstring;
char choice;
do
{
cout << "Type a sentence/word and I will determine if it is a Palindrome or not." << endl;
getline(cin, Pstring);
int last = Pstring.length()-1;
if (recursionPalindrome(Pstring, 0, last))
cout << "It is a Palindrome" << endl;
else
cout << "It is not a palindrome" << endl;
cout << "\nWould you like to test another for a Palindrome? ";
cin >> choice;
cin.ignore();
} while (choice == 'Y' || choice == 'y');
cout << endl;
return 0;
}
bool recursionPalindrome(string mString, int start, int end)
{
std::cout << mString[start] << " " << mString[end] << std::endl;
if (mString[end] == '\0')
returntrue;
elseif (mString[start] == mString[end])
return recursionPalindrome(mString, start + 1, end - 1);
elsereturnfalse;
}
When I click the little gear icon at the top right of my code above, it runs fine. Is it crashing on line 32? I think you want that to be if (mString[start] == '\0'). Try that. If that doesn't fix it, what compiler are you using and what is the exact error message.
the way you are testing, that sentence is not a palindrome. Yes, you are right, it is the white space, and also the commas. If you want it to test true, you'll have to remove all spaces, punctuation, and convert all the letters to one case before you pass the string to recursionPalindrome().