I have to write a program that checks whether a sentence is a palindrome or not.I had no problem checking a word, but checking a sentence that contains spaces and quoatation marks made results incorrect. Basically to solve the problem and ignore the spaces and marks, I copied the initial array to another array that doesnt contain those and worked with the second array.However, I'm not getting correct results.
void main()
{
cout<<"Enter the sentence you want to check if it is palindrome or not"<<endl;

char sentence1[100];
char sentence[100];

cin.getline(sentence1,100);


int length1=strlen(sentence1);
bool palindrome=true;
int j=0;
for(int i=0;i<length1;i++)
{
    if(isalpha(sentence1[i]))
    {for(j;j<length1;j++)
    sentence[j]=sentence1[i];
    }
}
int length=strlen(sentence);    

for (int j=0;j<(length/2);j++)
{
    if(tolower(sentence[j])!=tolower(sentence[length-j-1]))
    {
        palindrome=false;
        break;
    }
    else
        palindrome=true;
}
if(palindrome==true)
    cout<<"This is a palindrome"<<endl;
else
    cout<<"This is not a palindrome"<<endl;

}

Recommended Answers

All 4 Replies

The problem is at line 14. Using that loop is an issue. It should just be:

sencence[i]=sentence1[i];

Here is why. Take the sentence "The cow moved." Lets debug the code.
At i=0: T isalnum=true, sentence1 is copied from 0 to i(0) into sentence, sentence="T"
At i=1: h isalnum=true, sentence1 is copied from 0 to i(1) into sentence, sentence="Th"
At i=2: e isalnum=true, sentence1 is copied from 0 to i(2) into sentence, sentence="The"
At i=3: isalnum=false,sentence1 is not copied at all, sentence="The"
At i=4: c isalnum=true, sentence1 is copied from 0 to i(4) into sentence, sentence="The c" This is where the error occurs.

I'm not getting correct results.

In your FOR statement, if you get an alpha, you copy all the characters in sentence1 to sentence.
Why not just copy the one alpha you found.
When you're done with the FOR loops, how do you know you copied the sentence correctly? What's in sentence after the FORs?

I told you! Remove the for loop inside the if statement on line 13-14 and replace it with sentence[i]=sentence1[i] Seeing as both WaltP and I explained fairly clearly what was wrong I feel like the code you posted may not have been your own.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.