Creating a function to see if a word is a palindrome

I have to create a function in which i reverse the inputted word and compare if it is a palindrome with the original word using pointers.

Here my code...can someone place me in the right direction, and yes this is a homework assignment.

#include "std_lib_facilities.h"
#include <stdio.h>
#include <string.h>

//------------------------------------------------------------------------------

bool is_palindrome(const char* first, const char* last)
// first points to the first letter, last to the last letter
{
if (first<last) {
if (*first!=*last) return false;
return is_palindrome(++first,--last);
}
return true;
}

//------------------------------------------------------------------------------

istream& read_word(istream& is, char* buffer, int max)
// read at most max-1 characters from is into buffer
{
is.width(max); // read at most max-1 characters in the next >>
is >> buffer; // read whitespace terminated word,
// add zero after the last character read into p
return is;
}

//------------------------------------------------------------------------------

int main()
{
const int max = 128;
char s[max];
cout<<"Please enter a word an ill see if its a palindrome\n";
while (read_word(cin,s,max)) {
cout << s << " is";
if (!is_palindrome(&s[0],&s[strlen(s)-1])) cout << " not";
cout << " a palindrome\n";
}
}

//------------------------------------------------------------------------------
Last edited on
Try the following function

1
2
3
4
5
6
bool is_palindrome( const char* first, const char* last )
{
   while ( first != last && first != --last && *first == *last ) ++first;

   return ( first == last );
}


'last' points after the last character in a string. So the function shall be called as

is_palindrome( s, s + strlen( s ) );
Topic archived. No new replies allowed.