// https://forum.arduino.cc/t/help-doing-math-with-strings/1373788/
/*
calculator - Keep It Simple So Alto Smiles Serenely
- operates left to right only
- add, sub, mul, div ALL USE ADDITION:
-- add (positive direction)
-- sub (negative direction)
-- mul (recursive positive direction)
-- div (recursive negative direction)
*/
char array[] = "631 - 35 + 238 - 57 =";
int sizeofArray = sizeof(array) / sizeof(array[0]);
int pChar, pFloat, total, subtotal;
int signNew = 1, signOld = 1;
void setup() {
Serial.begin(115200);
for (int i = 0; i < sizeofArray; i++)
parse(array[i]);
}
void loop() {}
void parse(char pChar) {
switch (pChar) {
case '+': // sign indicates new number. default sign is +
signOld = signNew;
signNew = 1; // add positive direction
total = total + (subtotal * signOld); // store subtotal
Serial.print(subtotal * signOld);
Serial.print("+");
subtotal = 0; // clear subtotal when symbol is read
break;
case '-':
signOld = signNew;
signNew = -1;
total = total + (subtotal * signOld); // store subtotal
Serial.print(subtotal * signOld);
subtotal = 0; // clear subtotal when symbol is read
break;
case'=':
signOld = signNew;
total = total + subtotal * signOld;
Serial.print(subtotal * signOld);
Serial.print("=");
Serial.println(total);
subtotal = 0;
break;
case ' ': break; // ignore space
case '0'...'9':
pFloat = pChar - 48; // change char to float
subtotal *= 10; // shift subtotal left...
subtotal += pFloat; // ... add the new digit
default: break;
}
}