Printing a Sentence in Reverse Order with a Stack - C++ STL

C++ examples for STL:stack

Description

Printing a Sentence in Reverse Order with a Stack

Demo Code

#include <iostream>
#include <stack>
#include <string>

int main(int argc, const char* argv[]) {
    std::string cData;/*from  w w w  .  j av a  2 s  . com*/

    std::cout << "Enter a sentence: ";
    std::getline(std::cin, cData);

    std::stack<char> cStack;

    // add data to stack
    for (char& c : cData) {
        cStack.push(c);
    }

    // read stack in reverse order
    while (!cStack.empty()) {
        std::cout << cStack.top();
        cStack.pop();
    }

    std::cout << std::endl;

    return 0;
}

Result


Related Tutorials