Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/kimwalisch/calculator
C++ operator precedence parser
https://github.com/kimwalisch/calculator
c-plus-plus calculator
Last synced: 3 months ago
JSON representation
C++ operator precedence parser
- Host: GitHub
- URL: https://github.com/kimwalisch/calculator
- Owner: kimwalisch
- License: bsd-2-clause
- Created: 2013-11-08T09:29:27.000Z (about 11 years ago)
- Default Branch: master
- Last Pushed: 2024-03-10T18:11:43.000Z (11 months ago)
- Last Synced: 2024-10-11T21:57:21.835Z (4 months ago)
- Topics: c-plus-plus, calculator
- Language: C++
- Size: 28.3 KB
- Stars: 98
- Watchers: 12
- Forks: 63
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: COPYING
Awesome Lists containing this project
- stars - kimwalisch/calculator
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
#includeint 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;
}
```