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";
}
}
bool is_palindrome( constchar* first, constchar* 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