The below code is of a sentence palindrome checker. I'm a newbie programmer so I'm having a hard time debugging this code. It's showing incorrect output. For example, if the sentence is "A man, a plan, a canal: Panama" It's giving false as a result instead of true. (Blank spaces and punctuations are to be neglected.)
#include <iostream>
class Solution
{
public:
bool isPalindrome(std::string s)
{
int l, i;
i = 0;
l = s.length();
while (i <= (l - 1))
{
if (s[i] == ' ' || ispunct(s[i]) == true)
i++;
else if (s[l - 1] == ' ' || ispunct(s[l - 1]) == true)
l--;
else if (tolower(s[i]) == tolower(s[l - 1]))
{
l--;
i++;
}
else
return false;
}
return true;
}
};
int main(void)
{
Solution s;
const std::string text = "Panama";
std::cout << s.isPalindrome(text);
return 0;
}
The problem is very likely that the character classification functions (like e.g. ispunct
) does not return a bool
result.
They return an int
whose value can be any non-zero value for "true".
That means the condition like ispunct(s[i]) == true
might actually be false
for punctuation characters.
You need to use e.g. ispunct(s[i]) != 0
(or just plain ispunct(s[i])
) instead.