// // testCharStack.cpp // CSC 311 // John Rogers // // This program tests the CharStack class written for Assignment 3. // #include "charstack.h" #include #include #include using namespace std; // // isPalindrome checks whether the string parameter s contains // a palindrome, that is, a string that reads the same left-to-right // and right-to-left, ignoring spaces, case, and punctuation. // bool isPalindrome(const string& s) { string s2; CharStack cs; // The alphabetic characters in the argument string s are changed // to lower case and copied to s2. string::size_type index; for (index = 0; index < s.length(); index++) { if (isalpha(s[index])) { s2 += tolower(s[index]); } } // The characters of s2 are pushed onto the stack in // left-to-right order. for (index = 0; index < s2.length(); index++) { cs.push(s2[index]); } // The characters on the stack are in reverse order of // the characters of s2. They are compared and, if a // mismatch is found, false is returned. for (index = 0; index < s2.length(); index++) { if (cs.top() != s2[index]) return false; cs.pop(); } return true; } // // newline removes the newline character '\n' from the // input stream so that it won't interfere with later // input stream extractions. // void newline() { char c; do { cin.get(c); } while (c != '\n'); } // // askYesNoQuestion asks the question in its parameter and waits // until the user has typed a 'y' or an 'n', returning true // if a 'y' was typed. // bool askYesNoQuestion(string question) { char answer; do { cout << question; cin >> answer; answer = tolower(answer); } while (answer != 'n' && answer != 'y'); newline(); return answer == 'y'; } int main() { string s; // Test whether the basic stack functions of charStack work by calling // the palindrome tester. do { cout << "Enter a string to test whether it's a palindrome: "; getline(cin, s); if (isPalindrome(s)) { cout << "It is a palindrome!" << endl; } else { cout << "It is NOT a palindrome!" << endl; } } while (askYesNoQuestion("Do you wish to test another string? ")); // Test whether growing the stack automatically works correctly. CharStack cs; for (int index = 1; index <= 1000; index++) { cs.push(' '); } return 0; }