简体   繁体   English

布尔值不会在回文函数(C ++)中调整为false

[英]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. 出于某种原因,在我的第二次或第三次迭代中,if(beg!= end)不会返回false。 It returns false properly if I input, for instance, "bool", but not "blob." 如果我输入例如“ bool”而不是“ blob”,它将正确返回false。

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;
}

You should have used the return values of recursive calls: 您应该使用了递归调用的返回值:

        string new_str = str.substr(1, length - 1);
        return palindrome_check(new_str);
    }
    return true;

And you should have checked the length of the input string before you extract the first and the last character from it. 从中提取输入字符串的第一个和最后一个字符之前 ,您应该检查输入字符串的长度。

If you fix the two mistakes, it should be alright then. 如果您解决了两个错误,那么应该没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM