ok, the do/while caused it to loop, but the end statement is not terminating the program. Another problem I have is that the palindromes should not be case sensitive..
int main(void){
char word[81];
do{
bool palindrome=true;
cout << "Please enter a word" << endl;
cin>>word;
int length = strlen(word);
int(length/2);
if (length>0){
for(int i=0;i<(length);i++)
{
if(word[i]!=word[length-1-i])
palindrome=false;
}
}
if(palindrome==true)
{
cout << "The word is a palindrome" << endl;
}
else
{
cout << "The word is not a palindrome" << endl;
}
As I understand your code and the problem you are trying to solve, it seems that your test for a palindrome is incorrect. Dividing by 2 means you will miss odd lettered palindromes like 'level'. You use the code word[i] when I believe you mean to use the code word.length[i]. The latter examines each individual letter of the string in word. The former does not.
I don't know if a single character is considered a palindrome or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
string word;
do{
bool palindrome=true;
cout << "Please enter a word" << endl;
cin >> word;
int cnt = word.length()/2;
int wordLen = word.length()-1;
for(int i=0; i<cnt; i++, wordLen--) {
if (word[i] != word[wordLen]) {
palindrome = false;
break;
}
}
palindrome ? cout << "The word is a palindrome\n" : cout << "The word is not a palindrome\n";
}while (word != "END");
Hi Fresh Grass, I am working based on OP original code. I agree UI wise it is not intuitive but hey I am not supposed to write the whole program. I am supposed to help him resolve the critical portion of it. I believe the OP should be able to change the UI itself cuz afterall the detection of palindrome has already been done.
taken what sohguanh wrote you can use 'reverse' with strings to easily solve that problem:
1 2 3 4 5 6 7 8 9
do{
cout << "Please enter a word" << endl;
cin >> word;
string w2 = word;
reverse(w2.begin(), w2.end());
(word == w2) ? cout << "The word is a palindrome\n" : cout << "The word is not a palindrome\n";
}while (word != "END");
#include <iostream>
#include <fstream>
#include <cstring>
usingnamespace std;
int main(void){
char word[81];
do{
bool palindrome=true;
cout << "Please enter a word" << endl;
cin>>word;
int length = strlen(word);
for (int i=0; i<length; i++){
word[i] = toupper(word[i]);
}
int(length/2);
if (length>0){
for(int i=0;i<(length);i++)
{
if(word[i]!=word[length-1-i])
palindrome=false;
}
}
if(palindrome==true)
{
cout << "The word is a palindrome" << endl;
}
else
{
cout << "The word is not a palindrome" << endl;
}
} while (word!="END");
return(0) ;
}
if you use that char word[81]; this line while (word!="END"); compares 2 pointers which are always different. then you must use (0 == strcmp(word, "END"))