From 5046728ca7285f2a2139c14252ee657c0ab3abcf Mon Sep 17 00:00:00 2001 From: Adrian Kummerlaender Date: Thu, 30 Mar 2017 22:31:16 +0200 Subject: Minimal stack calculator REPL implementation --- repl.cc | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 repl.cc (limited to 'repl.cc') diff --git a/repl.cc b/repl.cc new file mode 100644 index 0000000..616d0f3 --- /dev/null +++ b/repl.cc @@ -0,0 +1,67 @@ +#include + +#include +#include +#include + +#include +#include + +bool is_number(const std::string& token) { + return std::all_of( + token.begin(), + token.end(), + [](char c) { return std::isdigit(c); } + ); +} + +bool is_primitive(const std::string& token) { + return token == "+" + || token == "-" + || token == "*" + || token == "."; +} + +void process(std::stack& stack, const std::string& token) { + if ( token == "+" ) { + const int b = stack.top(); + stack.pop(); + const int a = stack.top(); + stack.pop(); + + stack.push(a + b); + } else if ( token == "-" ) { + const int b = stack.top(); + stack.pop(); + const int a = stack.top(); + stack.pop(); + + stack.push(a - b); + } else if ( token == "*" ) { + const int b = stack.top(); + stack.pop(); + const int a = stack.top(); + stack.pop(); + + stack.push(a * b); + } else if ( token == "." ) { + std::cout << stack.top() << std::endl; + } +} + +int main(int, char*[]) { + std::stack stack; + std::string token; + + while ( std::cin.good() ) { + if ( std::cin >> token ) { + if ( is_number(token) ) { + stack.push(std::atoi(token.c_str())); + } else if ( is_primitive(token) ) { + process(stack, token); + } + } + } + + return 0; +} -- cgit v1.2.3