Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

boolean function returning false even though condition is satisfied to return true in c++. Why?

My function is a simple palindrome algorithm that is supposed to take an input integer (test), turn it into a string (test_s), then reverse that string in a new variable (test_s_reverse) then return true if test_s is equal to test_s_reverse.

bool is_palindrome(int test){
    test_s = to_string(test);
    test_length = test_s.length();
    for (int i=(test_length + 1); i>=0; i--){
        test_s_reverse += test_s[i];
    }
    if (test_s_reverse == test_s){
        return true;
    }
    else {
        return false;
    }
}

I created a main function to test results and using input 12321 the program returns false, even though cout for test_s_reverse is = 12321 and test_s = 12321.

What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should put test_length - 1 instead of test_lenght + 1, because in the new reversed string you have some extra characters which you can’t see if you print them.
.lenght() function returns you exacly the number of the characters in c++. So you either go with test_lenght, but you do i>0, or if you go in the loop with i>=0 you go with test_lenght – 1, so you will be sure that there are no blank characters at the end of new string.
But if you start with test_lenght, you will need to edit, since there is no character at test_lenght position

test_s_reverse += test_s[i-1];

If you use pure c++ code, it should look like this

bool is_palindrome(int test){
    string test_s = to_string(test);
    int test_length = test_s.length();
    string test_s_reverse;
    for (int i=(test_length); i>0; i--){
        test_s_reverse += test_s[i-1];
    }
    if (test_s_reverse == test_s){
        return true;
    }
    else {
        return false;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading