mardi 26 décembre 2017

Bool value not retuning false in palindrome function, C++

I've sadly read every post pertaining to this topic and can't seem to solve my issue. It's driving me mad.

For some reason on my second or third iteration, if (beg != end) won't return false. It returns false properly if I input, for instance, "bool", but not "blob."

I printed beg and end to make sure things are flowing properly, but still can't find where things are going wrong.

Thank you!!!

#include <iostream>
#include <string>
using namespace std;

bool palindrome_check (string str)
{
    string return_str;
    int length = str.length()-1;
    string beg = str.substr(0, 1);
    string end = str.substr(length, 1);

    if (beg != end)
    {
      //  cout << beg << " " << end << endl;
        return false;
    }

    else if ((str.length() > 2) && (str.length() != 0))
    {
        string new_str = str.substr(1, length - 1);
      //  cout << new_str << endl;
        palindrome_check(new_str);
    }
        return true;
}
int main ()
{

    string input;
    cout << "Enter a string: ";
    cin >> input;

    bool is_palindrome = palindrome_check (input);

    cout << is_palindrome << endl;
}

Aucun commentaire:

Enregistrer un commentaire