Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/kimwalisch/calculator

C++ operator precedence parser
https://github.com/kimwalisch/calculator

c-plus-plus calculator

Last synced: about 2 months ago
JSON representation

C++ operator precedence parser

Awesome Lists containing this project

README

        

# calculator

```calculator.hpp``` is a header-only C++ library for parsing and
evaluating integer arithmetic expressions e.g. ```"10 * (7 - 1)"```. It compiles with any
C++ compiler and works with any integer type e.g. ```int```,
```long```, ```uint64_t```.

calculator is a simple but fast
[operator-precedence parser](https://en.wikipedia.org/wiki/Operator-precedence_parser).

# Supported operators

```calculator.hpp``` uses the same operator precedence and associativity
as the C++ programming language and also supports the power operator.


Operator
Description


|
Bitwise Inclusive OR


^
Bitwise Exclusive OR


&
Bitwise AND


~
Unary Complement


<<
Shift Left


>>
Shift Right


+
Addition


-
Subtraction


*
Multiplication


/
Division


%
Modulo


**
Raise to power

# C++ API

Functions defined in ```calculator.hpp```.
```C++
int calculator::eval(const std::string& expression);

template
T calculator::eval(const std::string& expression);
```

# How to use it

```calculator::eval("1+2")``` takes a string with an integer arithmetic
expression as an argument, evaluates the arithmetic expression and returns
the result. If the expression string is not a valid integer arithmetic
expression a ```calculator::error``` exception is thrown.

```C++
#include "calculator.hpp"
#include
#include

int main()
{
try
{
int result = calculator::eval("(0 + ~(255 & 1000)*3) / -2");
std::cout << result << std::endl;

// 64-bit arithmetic
int64_t r64 = calculator::eval("2**60");
std::cout << r64 << std::endl;
}
catch (calculator::error& e)
{
std::cerr << e.what() << std::endl;
}

return 0;
}
```