I'm trying to make a code that prints out if the word is a palindrome or not.
but the code always tells me that the word is not a palindrom when i input a palindrome word. i think the error is in the for but i'm not sure.
#include<iostream>
#include<cctype>
usingnamespace std;
constint SIZE = 51;
int main ()
{
char line [SIZE];
char line2[SIZE];
int length;
cout<<"Enter a word no more than 50 characters."<<endl;
cin.getline(line,51);
length= strlen(line);
for (int count=length-1, i=0; count>=0; count--, i++)
line2[i]=line[count];
if(strcmp(line,line2)==0)
cout<<"The word is a palindrome."<<endl;
else
cout<<"The word is not a palindrome."<<endl;
system ("pause");
return 0;
}
First of all this declaration is invalid. There is no such constructor in class std::basic_string that accepts one argument of type char. So the compiler shall issue an error.
string words[4] = { "hi" , "hello" , "good" , '\0' }// same here
Moreover there is no any need to declare such a way arrays of std::string.:)
It is quite easy to figure out if a word is a palindrome once you figure out how. The best way to go about it is to make a function that does it for you. The function should return true if the words is a palindrome or false if it isn't.
To go about making this function just follow these steps.
1) Make you function, the function should return a bool and it should have only 1 parameter that is a const string& to the word you want to test. bool isPalin(const std::string &word) is how it could look.
2) In your function you need to reverse the string you want to test. The reason why you want to do this is because if the reversed string matches the original string it will be a palindrome. So figure out a way to reverse the string.
Hint: All you need to do is use the strings constructor with rbegin() and rend(). Remember that you can create a string by using 2 iterators.
3) Make a if else condition that test if the reversed string is equal to the original string. If it is return true. If it isn't return false.
And boom you have a function that can tell you if the string is a palindrome.
Let me know if you have any problems or don't understand anything.
The easiest way I can think of (If we are using std::string) is to use the constructor like so if (string(word.rbegin(), word.rend()) == word). Might not be the most efficient but is quite simple.
What other ways are there to go about it? I haven't really gave it that much thought so would be glad to know what other options are available.
Ahh nicely done. I like the use of std::next to only compare to the middle of the string.
Just making sure I understand it correctly, you are using std::equal to check the word from the beginning to the middle and from the last to the middle?
@Zereo
Just making sure I understand it correctly, you are using std::equal to check the word from the beginning to the middle and from the last to the middle?