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:
Output: 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:
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.
Related Topics¶
- Hand-Writing C++ FnOnce | C++那些事
- A Small C++ gRPC Project | C++那些事
- C++ Inter-Process Communication in Practice | C++那些事
- C++ Short URL Service Demo | C++那些事
- C++17 and SQLite Folder Size Statistics | C++那些事
- Google Benchmark Performance Testing | C++那些事
- C++20 Coroutine HTTP Server | C++那些事
- Protobuf ZeroCopy Serialization | C++那些事
- Accelerating Python with pybind11 | C++那些事