I'm tasked with a project to write a recursive function that will determine if a user inputted string is a palindrome or not. I think I have a very strong foundation of code for the problem, but it doesn't seem to work how I want it to.
I was doing some troubleshooting to figure out what was wrong and it appears that if my string is <= 8 characters long the length of the array automatically becomes 14 for some reason. Could use some troubleshooting and input from people better at c++ than myself.
Here is my code:
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
bool isPalindrome(char[], int, int);
int main()
{
char palin[100],
lowerPalin[100];
cout << "Enter a line that might be a palindrome:" << endl;
cin.get(palin, 100);
for (int i = 0, x = 0; i < strlen(palin); i++) // this for loop will remove punctuation, white space and make it all lowercase
{
if((palin[i] != ' ') && (ispunct(palin[i]) == false))
{
lowerPalin[x] = tolower(palin[i]); // transfering inputted array into new array with just alpha characters
x++;
}
}
int low = 0,
high = strlen(lowerPalin);
if (isPalindrome(lowerPalin, low, high))
cout << "The string is a palindrome." << endl;
else
cout << "The string is NOT a palindrome." << endl;
return 0;
}
bool isPalindrome(char lowerPalin[], int low, int high)
{
if (lowerPalin[low] == lowerPalin[high])
return isPalindrome(lowerPalin, low + 1, high - 1);
if (lowerPalin[low] != lowerPalin[high])
return false;
return true;
}
I'm still trying to learn recursion as well, so if anything is wrong with my bottom function please let me know.
EDIT: Thank you all for the help! I was able to understand and fix my mistake thanks to you all. Also thanks for all the tips in your answers, it helps a new student, like myself, a lot!