Kelick Tech Hub

Build, learn & keep up — tech, Linux & sports news included.

C++ Calculator Project

Beginner•2–3 hours•functions, switch, input validation

A four-function calculator that reads expressions and handles bad input gracefully.

Share on X

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

Feature checklist

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

Compile and run

g++ -std=c++17 -o calculator calculator.cpp

Sample 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):
> quit

Try 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.

Open the browser demo in the classic site →

Related Beginner projects

← All 60 projects · Classic site (Learn & Sandbox)

Download Fake GPS