Your example
12 + (2 * 5)
= 22
Since term
is known at compile-time, this example is not very useful, and it simply outputs 22
in an endless loop.
Basic interactive console
If you use the input from Serial
, you can write a very basic interactive console. A String
has been used for conciseness, but this example could be rewritten with cstrings:
#include "tinyexpr.h"
void setup() {
Serial.begin(115200);
}
void loop() {
if (Serial.available() > 0) {
String expression = Serial.readStringUntil('\n');
Serial.print("> ");
Serial.println(expression);
int error;
double result = te_interp(expression.c_str(), &error);
if (error) {
Serial.print(" ");
for (int i = 0; i < error; i++) {
Serial.print(" ");
}
Serial.println("↑");
Serial.println("I didn't understand this part.");
} else {
Serial.printf(" = %.10g\n", result);
}
}
delay(50);
}
> 12 + 2 * 5
= 22
> 3^5
= 243
> exp(7)
= 1096.633158
> (1 + sqrt(5)) / 2
= 1.618033989
> 1 + 2 * 3 + 4 * 5
= 27
> sin(pi/2)
= 1
> sin(pi/3)
= 0.8660254038
If there's a syntax error somewhere, error
tells you the position of the first encountered error:
> 3 +
↑
I didn't understand this part.
> sin() * 5
↑
I didn't understand this part.
> 3 / (4 + 5 * 7
↑
I didn't understand this part.