void play(MSI& rank, VS& toks) { SS oprs; SD nums; string out = ""; char str[100]; cout << "# from infix to postfix!!!" << endl; for (VS::iterator i = toks.begin(); i != toks.end(); i++) { string tok = *i; cout << "There is a " << tok << ": "; if (is_num(tok)) { cout << "push to output" << endl; sprintf(str, "%.6lf ", stod(tok)); out += str; nums.push(stod(tok)); } else if (tok == ",") { cout << "flush the stack until '('" << endl; while (oprs.top() != "(") calc(oprs, nums, out); } else if (tok == ")") { cout << "flush the stack until '(' and check if there's a func" << endl; while (oprs.top() != "(") calc(oprs, nums, out); oprs.pop(); if (!oprs.empty() && is_func(oprs.top())) calc(oprs, nums, out); } else { cout << "push to stack" << endl; if ( is_unary(tok) && (i == toks.begin() || rank[*(i - 1)] > 0) ) oprs.push("u" + tok); else { while (!is_func(tok) && tok != "(" && !oprs.empty() && rank[oprs.top()] <= rank[tok]) { cout << "\t*** stack.top() has higher precedence" << endl; calc(oprs, nums, out); } oprs.push(tok); } } cout << "\tcurrent output: " << out << endl << "\tcurrent stack: " << oprs << endl; } while (!oprs.empty()) calc(oprs, nums, out); cout << "There is nothing left, so flush the stack to output" << endl << "\tcurrent output: " << out << endl << "#transformation completed!!!" << endl << "Postfix Exp: " << out << endl << "RESULT: " << nums.top() << endl << endl; }
ostream& operator<<(ostream& out, const SS& s) { VS v; SS ss = s; while (!ss.empty()) { v.PB(ss.top()); ss.pop(); } for (int i = v.size() - 1; i >= 0; i--) out << v[i] << ' '; return out; }