Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a C++ program that functions as a palindrome detector using stacks. Progr

ID: 663733 • Letter: C

Question

Create a C++ program that functions as a palindrome detector using stacks. Program Input: A string of characters and/or numbers, such as "dad," "sheep," or "1B34CX149" (Do not worry about or include spaces). Program Output: The program just simply must state if the string given to the program by the user is a palindrome or not. An example of how the interface for the user could look in the command prompt Please enter a string: kayak Your string is a palindrome! or Please enter a string: jaguar Your string is not a palindrome! How to do it: 1. Take the string given to the program by the user and push the string character by character onto the stack. Make sure you save the string given to the program by the user for later use 2. Once the entire string has been pushed onto the stack, pop the string off the stack character by character, and append each character that gets popped off the stack into a new string. 3. Once the stack is empty, compare the original string given to the program by the user to the new string that has been created by popping the characters off the stack. If the strings are equal, the string is a palindrome 4. The program does not have to worry about upper/lower case palindrome detection (For example: In ''Racecar," since the first ‘r' is uppercase and the second isn't your program doesn't have to detect it as a palindrome, but it should detect "racecar.")

Explanation / Answer


#include "Palindrome.h"
#include <string>
#include <iostream>

void Palindrome::makePalindrome()
{
    palindrome.push('t');
    palindrome.push('a');
    palindrome.push('c');
    palindrome.push('o');
    palindrome.push('c');
    palindrome.push('a');
    palindrome.push('t');
}

void Palindrome::testPalindrome()
{
    std::string charCombine;

    //Combines all chars into a string
    while (!palindrome.empty())
    {
        charCombine += palindrome.top();
        palindrome.pop();
    }

    if(charCombine == std::string(charCombine.rbegin(), charCombine.rend())) // Test to see if string is a palindrome, case matters
    {
        std::cout << charCombine << " is a plindrome" << std::endl;
    }
    else
    {
        std::cout << charCombine << " is not a plindrome" << std::endl;
    }
}


Palindrome.h
#ifndef PALINDROME_H
#define PALINDROME_H

#include <stack>

class Palindrome {

public:
    void makePalindrome();
    void testPalindrome();

private:
    std::stack<char> palindrome;
};


#endif