Skip to content

Last updated:2026-10-12

C++ Stack Calculator Design

Write a stack calculator with the following design:

  • Supports the +, -, *, / operations
  • Supports postfix input

For example:

2 3 +
Output:
5
How do we implement it?

The two most crucial questions are:

1.How to tokenize

2.How to implement the stack

1. How to Tokenize

First, define the input as a string separated by spaces; then we can use istringstream to split out each token. The basic framework is:

std::istringstream iss(expression);
std::string token;
while (iss >> token) {
}

2. How to Implement the Stack

For a calculator, the core is pushing onto and popping off the stack.

  • Push when a number is encountered
  • Pop and calculate when an operator is encountered

We can then write the framework:

if (isNumber(token)) {
  pushNumber(token);
} else if (isOperator(token)) {
  popAndCal(token);
} else {
  throw std::runtime_error("Invalid token in expression.");
}

popAndCal is the core of the calculation, for example:

void popAndCal(const std::string& token) {
  if (operandStack.size() < 2) {
    throw std::runtime_error("Invalid expression.");
  } else {
    double operand2 = operandStack.top();
    operandStack.pop();
    double operand1 = operandStack.top();
    operandStack.pop();
    double result = performOperation(operand1, operand2, token);
    operandStack.push(result);
  }
}

Then what we want is stored in the stack, and finally we just return the top.

Isn't that simple? Feel free to discuss it with me.

Comments