Created
May 28, 2025 17:57
-
-
Save vlaleli/137f8c2e3afda9dbbc8d820fe926ce70 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| using namespace std; | |
| const int MAX_LEN = 100; | |
| class Parser { | |
| const char* expr; | |
| int pos; | |
| public: | |
| Parser(const char* expression) { | |
| expr = expression; | |
| pos = 0; | |
| } | |
| char peek() { | |
| while (expr[pos] == ' ') pos++; | |
| return expr[pos]; | |
| } | |
| char get() { | |
| return expr[pos++]; | |
| } | |
| int number() { | |
| int result = 0; | |
| while (isdigit(peek())) { | |
| result = result * 10 + (get() - '0'); | |
| } | |
| return result; | |
| } | |
| int term() { | |
| int result = factor(); | |
| while (peek() == '*' || peek() == '/') { | |
| char op = get(); | |
| int next = factor(); | |
| if (op == '*') | |
| result *= next; | |
| else { | |
| if (next == 0) { | |
| cout << "Помилка: ділення на нуль!" << endl; | |
| exit(1); | |
| } | |
| result /= next; | |
| } | |
| } | |
| return result; | |
| } | |
| int factor() { | |
| if (peek() == '(') { | |
| get(); | |
| int result = expression(); | |
| if (peek() == ')') get(); | |
| else { | |
| cout << "Помилка: відсутня дужка!" << endl; | |
| exit(1); | |
| } | |
| return result; | |
| } else { | |
| return number(); | |
| } | |
| } | |
| int expression() { | |
| int result = term(); | |
| while (peek() == '+' || peek() == '-') { | |
| char op = get(); | |
| int next = term(); | |
| if (op == '+') | |
| result += next; | |
| else | |
| result -= next; | |
| } | |
| return result; | |
| } | |
| }; | |
| int main() { | |
| char input[MAX_LEN]; | |
| cout << "Введіть арифметичний вираз: "; | |
| cin.getline(input, MAX_LEN); | |
| Parser parser(input); | |
| int result = parser.expression(); | |
| cout << "Результат: " << result << endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment