Question

I'm having trouble with the first if statement, when the program enters the loop it skips over the if statement. My program is supposed to test if the input is a palindrome and then print it out, (the 'Reverse' array is just to print out the original phrase backwards if it passes through the test). If the palindrome is "madam I'm adam" the output should be "madamimadam" no capitalization or punctuation. I'm not sure if the arrays will take care of that or if I need another conditional test to take out those characters? If someone could please look over my code and tell me what's wrong/what I can do I'd greatly appreciate it.

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

No correct solution

OTHER TIPS

You Using assignment insted of using equality

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

Modified your code to work below

http://ideone.com/GnO6hB

Equality vs Assignment

= represents assignment so the statement test = 1 will set test to 1. Due to the int to bool conversion, if test is non-zero, it will convert to true. So in your code, every if(test...) will evaluate to true

To solve this problem, you should test for equality using ==.

And your logic is wrong in the first loop: test initialized to 0 and will never equal 1 so the first loop is useless. Try this

int test = 1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top