Calculator in C++

An expression calculator in C++, built up from the exercises in Stroustrup's Programming: Principles and Practice. It cuts what you type into tokens and evaluates them with a small grammar. You can use it in your browser and watch the tokens appear.

When
Nov to Dec 2021 (about 2 months)
Status
Online Runs in your browser, on this page.
Where
MSc coursework, PMI programming course
Built with
C++, Tokens and grammars, WebAssembly demo
Made as
Individual project

About the project

The interesting part is not the arithmetic but how the text gets there. A token stream turns the characters you type into tokens: a number, a name, an operator, a bracket. Three functions that call each other, for expressions, terms and primaries, then follow the grammar, which is what makes 2+3*4 come out as 14 and not 20.

Starting from the book's version I added curly brackets, a factorial operator that also works for non-integers (through the gamma function), variables with let and constants with const, underscores in names, a symbol table class, help and quit commands, square root and power functions, and k as a short way to write thousands.

The demo runs the original source file, compiled to WebAssembly. The token view uses the program's own token stream, so what you see is what the calculator really reads.

Try it yourself

Tokens of what you are typing

Type an expression to see its tokens.

Things to try

Loading the calculator…

Get in touch

Let’s talk if you have a project in mind.