字符串检查始终返回错误的回文

时间:2018-07-02 00:44:56

标签: c++ c++11

我正在编写一个程序来检查用户输入的字符串是否是回文 即使字符串是已知回文,我的程序也始终返回false。 我认为我的问题出在PalindromeChecker函数上,因为这总是将main函数中的answer变量设置为false。但是我不确定为什么总是这样。

#include "stdafx.h"
#include <iostream>
#include <String>

using namespace std;

char ReadPalIn(string Pal, int len)//converts the string into a char array
{
    char PalIn[100];
    if (len > 100)
    {
        cout << "ERROR: Palindrome possibliity too big" << endl;
        system("Pause");
    }
    else
    {
        for (int i = 0; i < len; i++)
        {
            PalIn[i] = Pal[i];
        }
    }
    return *PalIn;
}

bool PalindromeChecker(char Pal[],int start, int end)//checks recursively if a string is a palidrome
{
    if (start == end)
    {
        return true; //since there is only one character
    }
    else if (Pal[start] != Pal[end])
    {
        //cout << "hi" << endl;
        return false;//since that will be the case that decides when something stops being a palidrome
    }
    else if (start < end + 1)
    {
        //cout << "hi" << endl;
        return PalindromeChecker(Pal, start++, end--);//since we checked both the first and last characters of the char array for palandrominess. <- word of the year?
    }
    else
    {
        return true;//base case is the string is a palindrome
    }
}

int main()//test if a word is a palidrome using the functions
{
    int lengthOfPal = 0;
    string PalInd = "abba";
    bool Answer = true;
    cout << "Hello what string would you like to check?" << endl;
    getline(cin, PalInd);
    lengthOfPal = PalInd.length();
    cout << "You input is: " << PalInd << endl;
    cout << "Its Length is: " << lengthOfPal << endl;
    system("Pause");
    char PalIn[100] = { ReadPalIn(PalInd, lengthOfPal) };

    Answer = PalindromeChecker(PalIn, 0, lengthOfPal);
    if (Answer == true)
    {
        cout << PalInd << ": is a palidrome" << endl;
        system("Pause");
    }
    else if(Answer == false)
    {
        //cout << "hi" << endl;
        cout << PalInd << ": is not a palidrome" << endl;
        system("Pause");
    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

您总是返回false,因为您没有在比较自己认为的内容。

在最初调用PalindromeChecker()时,您将lengthOfPal用作end参数。由于字符串是零索引的,因此您的初始调用应使用lengthOfPal - 1

假设您的字符串是abbaa字符位于[0][s.length() - 1](索引[3])处。

您将要遇到的另一个问题是在递归调用中传递start++end--作为参数。这些是后递增和后递减运算符,这意味着它将把startend current 值传递到递归调用中,然后 then < / em>调整其值。由于您已将函数设置为递归,因此每次都只会对startend使用相同的值。可以使用预递增++start和预递减--end来避免此问题。