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

c++ palindrome program using arrays

本文关键字:回文 程序 C++ 数组      更新时间:2023-10-16

我在使用第一个if语句时遇到问题,当程序进入循环时,它会跳过if语句。我的程序应该测试输入是否是回文,然后将其打印出来,("反向"数组只是在通过测试时向后打印出原始短语)。如果回文是"女士我是亚当",则输出应该是"女士",没有大写或标点符号。我不确定数组是否会解决这个问题,或者我是否需要另一个条件测试来删除这些字符?如果有人可以查看我的代码并告诉我出了什么问题/我能做什么,我将不胜感激。

#include <iostream>
#include <string>
using namespace std;
int main()
{
    //Variables and Arrays
    char Phrase[80];
    char Reverse[80];
    char* Palindrome = Reverse;
    int i, j, test = 1;
    cout << "Please enter a sentence to be reversed: ";
    cin >> Phrase;
    cin.getline(Phrase, 80);
    int length = strlen(Phrase);
    for(i = 0; i < (length/2); i++) // do a loop from 0 to half the length of the string
    {
        if(test == 1) // test for palindrome
        {
            if(Phrase[i] != Phrase[length-i-1]) // check if the characters match
            {
                test = 0; // if they don't set the indicator to false
            }
        }
        else
        {
            break; // if it is not a palindrome, exit the for loop
        }
    }
    if(test == 1) //test to print out the phrase if it's a palindrome
    {
        cout << "Phrase/Word is a Palindrome." << endl;
        for(j = strlen(Phrase) - 1; j >= 0; Palindrome++, j--)
        {
            *Palindrome = Phrase[j];
            cout << "The reverse is: " << Reverse << endl << endl;
        }
    }
    else
    {
        cout << "Phrase/Word is not a Palindrome." << endl;
    }
    system("Pause");
    return 0;
}

你 使用赋值而不是使用相等

 if(test = 1) //Logical error. which will always be true
//it should be
if(test == 1)

修改了您的代码以在下面工作

http://ideone.com/GnO6hB

平等赋值

=表示赋值,因此语句test = 1test设置为 1。由于 int 到 bool 的转换,如果 test 不为零,它将转换为 true 。因此,在您的代码中,每个if(test...)的计算结果都将true

要解决此问题,您应该使用 == 来测试相等性。

你的逻辑在第一个循环中是错误的:test初始化为 0 并且永远不会等于 1,所以第一个循环是无用的。试试这个

int test = 1;