I need to use a stack and queue to test for a palindrome. The program works fine with one word answers such as racecar. The problem i am having is that i need to ignore space and punctuation so i can test sentences and questions. Any help is appreciated.
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
int main()
{
bool palindrome = true;
char character;
stack<char> stack;
queue<char> queue;
char a;
char b;
cout << "Enter a string; press return." << endl;
cin >> character;
while (isalpha(character))
{
if (isalpha(character))
{
character = tolower(character);
}
stack.push(character);
queue.push(character);
cin.get(character);
}
while (!queue.empty())
{
a = stack.top();
b = queue.front();
stack.pop();
queue.pop();
if (a != b)
palindrome = false;
}
if (palindrome)
cout << "String is a palindrome." << endl;
else
cout << "String is not a palindrome." << endl;
system("pause");
return 0;
}
Move
stack.push(character);
queue.push(character);
to the if statement, like so:
if (isalpha(character))
{
character = tolower(character);
stack.push(character);
queue.push(character);
}
You are checking whether it's an alpha character, this way, you won't even load the non-letter characters in the stack/queue. If you want to allow using non alpha characters and to just filter them out, consider using while(cin >> character)
so it doesn't terminate on the first non-letter char.
You could do something simple like:
while (!queue.empty())
{
While(isspace(stack.top())
{
stack.pop();
}
While(isspace(queue.front())
{
queue.pop();
}
a = stack.top();
b = queue.front();
stack.pop();
queue.pop();
if (a != b)
palindrome = false;
}
Reference: http://www.cplusplus.com/reference/cctype/isspace/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.