Hey guys, i'm having problems with my palindrome function. Sometimes when it is a palindrome with a space it declares that it isnt a palindrome and if there's a punctuation in the end, it declares it isnt a palindrome. Any suggestions?
void palindrome ()
{
char word[256]; //how to ignore other data type
int length, i, j;
cout << "Enter a word, phrase or sentence: ";
cin >> word;
length = strlen(word);
for(int i=0; i < length-1; i++)
{
if(ispunct(word[i]||isspace(word[i])))
word[i]= 'b';
}
for (i=0, j=length-1; j>i; j--, i++)
{
if((word[i]) != (word[j]))
{
cout <<"No it is not a palindromen" << endl;
}
else
cout <<"Yes, it is a palindromen"<< endl;
break;
}
cout << "Press <enter> to continue.. ";
fflush ( stdin );
cin.get ();
}
It shouldn't even work for palindromes without punctuation. Try racecar, and I'm sure it won't work. I'm sorry to say that your logic has several major flaws.
line 11,12:
1 2
if(ispunct(word[i]||isspace(word[i])))//you're missing a parenthesis before ||
word[i]= 'b';//why 'b'? That doesn't help anything
Your second for loop is also not going to work. You're breaking after the first comparison every time.
I recommend setting up a loop for the input and ignoring any invalid characters.
and what's up with the break statement? your for loop is not a for loop at all since you're breaking out of it during the first iteration no matter what