Recursive Palindrome Detector

I've written a program that is supposed to have a recursive function that detects whether or not an input string character is a palindrome.

I have a program that removes all the white space and punctuation, which seems to work just fine, but when I actually run the string through the palindrome detector, it always returns false, except in the case that the value entered is only one letter long, in which case it returns true.

I've gone through the logic of my palindrome detection function, and it seems solid, but I haven't been able to figure out why it keeps returning false.

My base case is when there are no more character to look through (ie, when first and last are at the same position or adjacent positions in the string).

I'm still troubleshooting, but if anyone could enlighten me as to why this is happening, I'd be very grateful.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <string>

using namespace std;

string removeChar(string);
bool isPal(string&, int, int);

int main()
{
	string testSentence;
	string newSentence;
	int first = 0;
	int last = string::npos;

	cout << "Palindrome Detection Program" << endl;
	cout << "Enter a word or sentence, and the program will tell whether or not it is a palindrome." << endl;

	getline(cin, testSentence);

	newSentence = removeChar(testSentence);

	cout << "Your entry " << (isPal(newSentence, first, last) ? "is a palindrome." : "is not a palindrome.") << endl;
	

	cin.get();

	return 0;
}

string removeChar(string testSentence)
{
	string newSentence;

	for (unsigned int c = 0; c < testSentence.length(); c++)
	{
		if (isalnum(testSentence[c]))
		{
			newSentence += testSentence[c];
		}

	}

	return newSentence;
}

bool isPal(string& newSentence, int first = 0, int last = string::npos)
{

	if (last = string::npos)
	{
		last = (newSentence.length()-1);
	}
	if (newSentence[first] == newSentence[last])
	{
		if ((first-last) == 0)
		{
			return true;
		}
		else if (first == (last - 1))
		{
			return true;
		}
		else
		{
			return isPal(newSentence, first+1, last-1);
		}
	}
	else
	{
		return false;
	}
}
closed account (D80DSL3A)
Line 50. Should be ==, not =.
If I had a nickel for every time I've overlooked = when it should be == I would be a much wealthier man.

Thanks, fun2code. Program works fine now, except I need to add another function that will make all the letters in the string the same case (upper or lower, that is), which I will tackle tomorrow.
Topic archived. No new replies allowed.