#include #include #include #include #include using namespace std; float processStack(stack &s); bool isOperator(string str); template T fromString(string x) { T retval; istringstream strin(x); strin >> retval; return retval; } template string toString(T x) { ostringstream strout; strout << x; return strout.str(); } void prompt() { cout << ">> "; } vector split(string line, string separator) { vector retval; char * cstr, * p; cstr = new char [line.size() + 1]; strcpy(cstr, line.c_str()); p = strtok(cstr, separator.c_str()); while (p != NULL) { retval.push_back(p); p = strtok(NULL, separator.c_str()); } delete cstr; return retval; } bool isOperator(string str) { string operators [] = {"+", "-", "*", "/"}; for (int i = 0; i < 4; i++) { if (str == operators[i]) return true; } return false; } float processStack(stack &s) { string str(""); if (!s.empty()) { str = s.top(); s.pop(); if (!isOperator(str)) { return fromString(str); } else { string stra = s.top(); float ia = 0.0; if (isOperator(stra)) ia = processStack(s); else { ia = fromString(stra); s.pop(); } string strb = s.top(); float ib = 0.0; if (isOperator(strb)) ib = processStack(s); else { ib = fromString(strb); s.pop(); } if (str == "+") { return ia + ib; } else if (str == "-") { return ia - ib; } else if (str == "*") { return ia * ib; } else if (str == "/") { return ia / ib; } } } return 0; } int main (int argc, char *argv[]) { stack s; char buff [8126]; prompt(); while (cin.good() && cin.getline(buff, 8126)) { string line(buff); if (line == "bye") return 0; vector tokens = split(line, " "); for (size_t i = 0; i < tokens.size(); i++) { s.push(tokens[i]); } cout << "result: " + toString(processStack(s)) << endl; prompt(); } return 0; }