// // Program name: palindrome // Author: B. Massingill // // Input: a sequence of characters, ended by ctrl-D (end of file) // Output: a message saying whether the input forms a palindrome // #include #include // for character library functions // // Function name: isPalindrome // // Precondition: // phrase contains phraseLength characters that we want to // check -- do they form a palindrome? // Postcondition: // return value is true if the characters form a palindrome, // false otherwise // // Note that the test skips all but alphabetic characters and is // not case-sensitive. // bool isPalindrome(char phrase[], int phraseLength) ; // // main program // int main() { const int MAXLEN = 100 ; char inchars[MAXLEN] ; char tempchar ; int numchars = 0 ; cout << "Enter a phrase, ctrl-D to end\n" ; while (cin.get(tempchar)) { if (numchars >= MAXLEN) { cout << "Too long!\n" ; return -1 ; } inchars[numchars++] = tempchar ; } if (isPalindrome(inchars, numchars)) cout << "It's a palindrome\n" ; else cout << "It's not a palindrome\n" ; return 0 ; } // function definition -- see prototype above for documentation bool isPalindrome(char phrase[], int phraseLength) { int left = 0 ; // leftmost character not // yet compared int right = phraseLength - 1 ; // rightmost character not // yet compared bool result = true ; while (result && left < right) { if (!isalpha(phrase[left])) left += 1 ; else if (!isalpha(phrase[right])) right -= 1 ; else result = tolower(phrase[left++]) == tolower(phrase[right--]) ; } return result ; }