Palindrome Testing with Stacks - C++ STL

C++ examples for STL:stack

Description

Palindrome Testing with Stacks

Demo Code

#include <ctype.h>
#include <iostream>
#include <stack>
#include <string>

int main(int argc, const char* argv[]) {
    std::string cData;// w w w .  java 2  s.  c  o m
    std::string cSanitised;

    std::stack<char> cStack;

    std::cout << "Enter a string for palindrome test: ";
    std::getline(std::cin, cData);

    // sanitise data - remove spaces and punctuation
    for (char& c : cData) {
        if (isspace(c) || ispunct(c)) continue;

        cSanitised += tolower(c);
        cStack.push(tolower(c));
    }

    // build comparison string from stack
    std::string rData;

    while (!cStack.empty()) {
        rData += cStack.top();
        cStack.pop();
    }

    std::cout << cData << " is" << (rData == cSanitised ? " " : " not ")
              << "a palindrome" << std::endl;

    return 0;
}

Result


Related Tutorials