Some well-known English palindromes are, \"Able was I ere I saw Elba\", \"A man,
ID: 653762 • Letter: S
Question
Some well-known English palindromes are, "Able was I ere I saw Elba", "A man, a plan, a canal -
Panama!", "Madam, I'm Adam" or "Madam in Eden, I'm Adam", "Doc, note: I dissent. A fast
never prevents a fatness. I diet on cod", "Never odd or even", and "Rise to vote, sir".
This program is to extend the parlindrome program (parlindrome.cpp available from the course
page) discussed in class to be able to check whether a string is a parlindrome even if it includes
space and/or punctuation marks.
This is parlindrome.cpp file
Explanation / Answer
// Palindrome.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <queue>
#include <stack>
#include <string>
using namespace std;
// declarations
bool checkPalindrome(string line);
// main function
int main ()
{
string line;
while (true)
{
cout << "Enter a string: ";
getline(cin,line);
if (line == "")
break;
else
{
if (checkPalindrome(line))
cout << "This is a palindrome." << endl;
else
cout << "This is not a palindrome." << endl;
}
}
return 0;
}
// This function checks whether a string is a palindrome
// by storing the string in a stack and a queue
// Stack reverse the direction of the characters in the string while
// Queue maintains original direction of the characters in the string
// If the top/front characters from the stack and queue are all the same,
// then the string is a palindrome, otherwise, not
bool checkPalindrome(string line)
{
queue<char> myQueue;
// Create an empty queue
stack<char> myStack;
for (int i=0; i<line.length(); i++)
{
if ((static_cast<int>(line[i]) > 64 && static_cast<int>(line[i]) < 91) || (static_cast<int>(line[i]) > 96 && static_cast<int>(line[i]) < 123))
{
myQueue.push(tolower(line[i]));
myStack.push(tolower(line[i]));
}
}
// Remove words and print
while (!myQueue.empty())
{
char q, s;
q = myQueue.front();
myQueue.pop();
s = myStack.top();
myStack.pop();
if (q != s)
return false;
}
if (myQueue.empty())
return true;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.