C++ Calculator Project
A four-function calculator that reads expressions and handles bad input gracefully.
What you will build
Your first real program: a calculator that takes two numbers and an operator, computes the result, and keeps going until the user quits. It looks trivial, but it forces you to think about input parsing, division by zero, and structuring code into small functions instead of one giant main().
What you will learn
- Reading and validating user input with std::cin
- Branching with switch statements
- Splitting logic into reusable functions
- Guarding against divide-by-zero and bad operators
Feature checklist
- Add, subtract, multiply, divide
- Reject division by zero with a clear message
- Loop so the user can chain calculations
- Handle non-numeric input without crashing
- Support decimal results with sensible formatting
Starter code
#include <iostream>
double applyOp(double a, double b, char op, bool& ok) {
ok = true;
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/':
if (b == 0) { ok = false; return 0; }
return a / b;
default: ok = false; return 0;
}
}
int main() {
double a, b; char op;
std::cout << "Enter: number op number (e.g. 12 * 3)\n";
while (std::cin >> a >> op >> b) {
bool ok;
double r = applyOp(a, b, op, ok);
if (ok) std::cout << "= " << r << "\n";
else std::cout << "Invalid operation.\n";
std::cout << "Next (or Ctrl+C to quit): ";
}
}Full walkthrough
Step 1: Create the file and the skeleton
Create a file called calculator.cpp and start with #include <iostream> — that single header gives you std::cin and std::cout, which are all this program needs. Add an empty main() and compile it right away: an empty program that builds is your safety net, because every error from here on is caused by the last thing you typed.
#include <iostream>
int main() {
// the calculator loop will live here
}Step 2: Write applyOp() — one function that does the maths
The starter code keeps every calculation inside applyOp(double a, double b, char op, bool& ok). A switch on the operator char returns a + b, a - b, a * b or a / b, and the ok reference parameter reports whether the operation was legal. Returning the answer while reporting success separately is the trick: a double alone cannot say 'that was invalid'.
double applyOp(double a, double b, char op, bool& ok) {
ok = true;
switch (op) {
case '+': return a + b;
case '-': return a - b;
// ...
}
}Step 3: Guard division by zero inside the switch
Inside case '/', check b == 0 before dividing. If it is zero, set ok = false and return 0 — the caller will print the error. Dividing by zero with doubles would silently produce inf, and with integers it would crash, so this one if is what makes the program feel professional.
Step 4: Build the read–compute–print loop in main()
main() declares double a, b and char op, prints the prompt once, then loops on while (std::cin >> a >> op >> b). The genius of that condition: extraction reads a whole '12 * 3' line in one go, and when the input runs out or turns to garbage the loop simply ends. Each pass calls applyOp(), then prints '= ' plus the result, or 'Invalid operation.' when ok is false.
while (std::cin >> a >> op >> b) {
bool ok;
double r = applyOp(a, b, op, ok);
if (ok) std::cout << "= " << r << "\n";
else std::cout << "Invalid operation.\n";
std::cout << "Next (or Ctrl+C to quit): ";
}Step 5: Understand why bad input ends the program (and why that is OK)
If the user types letters instead of numbers, std::cin enters a fail state and the while condition goes false, so the program exits cleanly instead of spinning forever. The feature checklist asked for 'no crashing on non-numeric input' — this pattern delivers exactly that with zero extra code.
Step 6: Test it like a user, not like its author
Run the four operations with numbers whose answers you know: 12 * 3 = 36, 10 / 4 = 2.5. Then attack it: divide by zero, use % (an operator that does not exist yet), type words. Each attack should produce 'Invalid operation.' or a clean exit — never a crash or a wrong answer.
Step 7: Finish the checklist items
Decimals already work because everything is double. The last checklist item — sensible formatting — is one line: let the default formatting do its job, or use std::setprecision from <iomanip> if you want fixed decimals everywhere.
Common mistakes
- Forgetting case '/' needs its own block braces in a switch when you declare variables inside it — wrap the case body in { } to avoid 'jump bypasses variable initialization' errors.
- Checking b == 0 only in main() instead of inside applyOp() — then the guard is skipped the first time you reuse the function elsewhere.
- Using int for the numbers, so 10 / 4 prints 2 instead of 2.5 and users think the calculator is broken.
Compile and run
g++ -std=c++17 -o calculator calculator.cppSample run
$ ./calculator
Enter: number op number (e.g. 12 * 3)
> 12 * 3
= 36
Next (or Ctrl+C to quit):
> 10 / 4
= 2.5
Next (or Ctrl+C to quit):
> 7 / 0
Invalid operation.
Next (or Ctrl+C to quit):
> 9 + 5
= 14
Next (or Ctrl+C to quit):
> quitTry it in your browser
This project has a browser demo in the classic site. The demo is a browser re-implementation of the same logic, not the compiled C++ program: The web version of the Calculator project — same logic as the C++ starter: read a value, apply an operator, repeat.