r/programminghomework • u/TheAbortedPancake • Mar 25 '17
[C++] word level palindrome program with stacks and queues
I have a good portion of my program finished, I am just trying to figure out how to do some final things to it. I want the program to only check for letters a through z and A = Z, treating uppercase and lower case as the same thing. I want it to ignore any other characters and to just realize word level palindromes, not sentence level, so for example a%345b@a c24&c8dd9cc would be a word level palindrome since the program would ignore the numbers and special characters and only look at each word or set of letters as a candidate. Since uppercase and lowercase will be treated the same, something like AbBa baB should also come back as a word level palindrome. Here is the code I have so far. Thanks for any help.
include <cassert> // Provides assert
include <cctype> // Provides isalpha, toupper
include <iostream> // Provides cout, cin, peek
include <queue> // Provides the queue template class
include <stack> // Provides the stack template class
using namespace std;
int main() {
queue<char> q;
stack<char> s;
char letter;
queue<char>::size_type mismatches = 0; // Mismatches between queue and stack
cout << "Enter a line and I will see if it's a palindrome:" << endl;
while (cin.peek() != '\n')
{
cin >> letter;
if (isalpha(letter))
{
q.push(toupper(letter));
s.push(toupper(letter));
}
}
while ((!q.empty()) && (!s.empty()))
{
if (q.front() != s.top())
++mismatches;
q.pop();
s.pop();
}
if (mismatches == 0)
cout << "That is a palindrome." << endl;
else
cout << "That is not a palindrome." << endl;
cin.ignore(2);
return 0;}
2
u/cs313131 Mar 26 '17
If I understand what you're asking correctly, your program currently finds sentence level palindromes, and you want it to find word level palindromes?
So you basically want to run this program on each word in the string, as opposed to the whole string. If it doesn't fail on any of the words, then you have a word level palindrome. If it fails any of them, it's not a word level palindrome.
Is that right?
1
u/thediabloman Mar 26 '17
I think you need to do some pre-provessing on your string to make it easier to work with.
Split your string by spaces to get each word in a list then clean each word for special characters by using something like this.