c ++使用数组的回文程序

时间:2014-01-29 21:54:55

标签: c++ arrays palindrome

我的回文计划有问题。我需要使用数组并显示如果没有.push或.pop,推送和弹出将如何工作。我遇到的麻烦是,当我输入一个3个字母的单词时,它会说是的它是一个回文,但如果我输入一个4个或更多字符的单词,它就会说不是回文,即使它是。恩。皮艇。不要看我出错的地方。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    char original[13];
    int stkptr=-1;
    int x = strlen(original)-1;


    cout <<"Enter a character"<<endl;

    for( ++stkptr ; stkptr<13;stkptr++)
    //store user input into the array
    {

        cin>>original[stkptr];

        if(original[stkptr]=='0')
            break;

        cout<<original[stkptr]<<"  Stack pointer is: "<<stkptr<<endl;



    }
    //POP
    for (--stkptr; stkptr>=0;stkptr--)
        cout<<original[stkptr]<<" Stack pointer is: "<<stkptr<<endl;



    for(int i = 0; i <= x; i++)
    {
        if (original[i] == original[x-i])
        {
            continue;
        }
        else
        {
            cout<<"\nNot a palidrome\n"<<endl;
            system("pause");
            return 0;
        }
    }

    cout << "\nIndeed Palidrome\n"<<endl;
    system("pause");
    return 0;
}   

2 个答案:

答案 0 :(得分:0)

bool checkIsPalindrome(string s){
    int nLength = s.length();
    string s1, s2;
    if(nLength & 1) // is Odd
        nLength--;

    nLength = nLength/2;

    //take the first half
    s1 = s.substr(0,nLength);

    //pop off the last half of characters into the string
    for(int i = s.length()-1; i > nLength; i--)
       s2+= s.at(i);

    if(s1 == s2)
        return true;
    else
        return false;

}

答案 1 :(得分:0)

虽然你的逻辑过于复杂,但我会说出当前代码的错误。

x你出错了。当没有“字符串”时,将它初始化为字符串长度(此外,您的char数组最后应该有一个\0,以便strlen()工作)。在stkptr-1之前将x分配给pop,然后移除pop

在你的循环中,你应该只迭代到数组的一半,因为你要从开头和结尾比较char-by-char

for(int i = 0; i <= x/2; i++)