C++ examples for STL:stack
Four-function postfix calculator.
#include <iostream> #include <stack> #include <string> #include <cmath> using namespace std; int main()/*from www . j a v a2 s .com*/ { stack<double> stck; double a, b; string s; do { cout << ": "; cin >> s; switch(s[0]) { case 'q': // quit the calculator break; case '.': // show top-of-stack cout << stck.top() << "\n"; break; case '+': // add if(stck.size() < 2) { cout << "Operand Missing\n"; break; } a = stck.top(); stck.pop(); b = stck.top(); stck.pop(); cout << a+b << "\n"; stck.push(a+b); break; case '-': // subtract // See if user entered a negative number. if(s.size() != 1) { // Push value onto the stack. stck.push(atof(s.c_str())); break; } // otherwise, is a subtraction if(stck.size() < 2) { cout << "Operand Missing\n"; break; } a = stck.top(); stck.pop(); b = stck.top(); stck.pop(); cout << b-a << "\n"; stck.push(b-a); break; case '*': // multiply if(stck.size() < 2) { cout << "Operand Missing\n"; break; } a = stck.top(); stck.pop(); b = stck.top(); stck.pop(); cout << a*b << "\n"; stck.push(a*b); break; case '/': // divide if(stck.size() < 2) { cout << "Operand Missing\n"; break; } a = stck.top(); stck.pop(); b = stck.top(); stck.pop(); cout << b/a << "\n"; stck.push(b/a); break; default: // push value onto the stack stck.push(atof(s.c_str())); break; } } while(s != "q"); return 0; }