diff options
Diffstat (limited to 'week10/ex5.cpp')
| -rw-r--r-- | week10/ex5.cpp | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/week10/ex5.cpp b/week10/ex5.cpp new file mode 100644 index 0000000..895c729 --- /dev/null +++ b/week10/ex5.cpp @@ -0,0 +1,44 @@ +#include <iostream> +#include <cstring> + +void skipWhitespaces(char*& str) { + while (*str == ' ') str++; +} + +int calculateExpression(char*& expr) { + if (*expr == '\0') return 0; + + skipWhitespaces(expr); + + // Ако започваме с цифра, връщаме числото и го пропускаме в израза + if ('0' <= expr[0] && expr[0] <= '9') { + int ret = atoi(expr); + while ('0' <= *expr && *expr <= '9') expr++; + return ret; + } + + expr++; // пропускаме ( + int leftHandSide = calculateExpression(expr); + skipWhitespaces(expr); + + char op = *expr; + expr++; + + skipWhitespaces(expr); + int rightHandSide = calculateExpression(expr); + + skipWhitespaces(expr); + expr++; // пропускаме ) + + if (op == '+') { + return leftHandSide + rightHandSide; + } + return leftHandSide * rightHandSide; +} + +int main() { + char buf[1025]; + std::cin.getline(buf, 1025); + char* ptrCopy = buf; + std::cout << calculateExpression(ptrCopy) << std::endl; +} |
