-2

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;
}
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • 1
    First create a simple `main` function which uses your class to pass the failing sentence. Then you can use a debugger to step through the code, statement by statement while monitoring variables and their values. I also recommend that you create temporary variables to store intermediate results of functions calls, like for example `auto temp1 = ispunct(s[i]);` and then use `temp1 == true` instead of `ispunct(s[i])==true`. – Some programmer dude Aug 04 '20 at 06:55
  • You probably need to replace the `if` statements with `while` loops. But do learn how to debug by yourself. – Benny K Aug 04 '20 at 06:58
  • Please avoid comparing boolean expressions (in this case, represented as an `int`) to `true`. It's useless and can (and does in this case) damage your code. – Roy Avidan Aug 04 '20 at 07:36

2 Answers2

3

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

And also, that is not how one checks for palindrome. I suggest the following code:

#include <iostream>

int main() {
    std::string str;
    std::cin >> str;
    for (auto i = 0, j = str.size() - 1; i < j; i++, j--) {
        if (//check for punctuation) {

        }
        else if (str.at(i) != str.at(j)) {
            //not a palindrome
            break;
        }
    }
    return 0;
}
kesarling He-Him
  • 1,944
  • 3
  • 14
  • 39