std::stack を使うのはあんまりな気がしてきたので、一応手動バージョンを書きます。エラー処理とかは手抜きです。
#include <iostream> #include <array> #include <string> #include <sstream> using namespace std; static bool isOperator(const string& st) { return st[0] == '+' || st[0] == '-' || st[0] == '*'; } class Stack { public: Stack() : stack(), index() {}; virtual ~Stack() {}; void push(const string& in) { stack[index] = in; index++; } string pop() { index--; return stack[index]; } private: array<string, 100 + 200> stack; int index; }; int main() { Stack st; string op1, op2, op, line, elem; int op1_i, op2_i, ans; // input line. getline(cin, line); stringstream ss(line); // sprit. while (getline(ss, line, ' ')) { st.push(line); if (isOperator(line)) { op = st.pop(); op2 = st.pop(); op1 = st.pop(); op1_i = stoi(op1); op2_i = stoi(op2); switch (op[0]) { case '+': ans = op1_i + op2_i; break; case '-': ans = op1_i - op2_i; break; case '*': ans = op1_i * op2_i; break; default: break; } st.push(to_string(ans)); } } cout << st.pop() << endl; return 0; }