C++ ПРОСТЕНЬКИЙ МАТЕМАТИЧЕСКИЙ ПАРСЕР
#include <iostream>
#include <fstream>
#include <stack>
#include <cmath>
using namespace std;
int priority(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
if (op == '^') return 3;
return 0;
}
bool is_operator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
double apply_operator(char op, double b, double a) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
case '^': return pow(a, b);
default: return 0;
}
}
double calculate(string expression) {
stack values;
stack operators;
for (int i = 0; i < expression.length(); i++) {
if (expression[i] == ' ') continue;
if (expression[i] == '(') {
operators.push(expression[i]);
} else if (expression[i] == ')') {
while (operators.top() != '(') {
char op = operators.top();
operators.pop();
double a = values.top();
values.pop();
double b = values.top();
values.pop();
values.push(apply_operator(op, b, a));
}
operators.pop();
} else if (isdigit(expression[i])) {
double value = 0;
while (i < expression.length() && (isdigit(expression[i]) || expression[i] == '.')) {
value = (value * 10) + (expression[i] - '0');
i++;
}
i--;
if (!operators.empty() && operators.top() == '-') {
operators.pop();
value = -value;
}
values.push(value);
} else if (is_operator(expression[i])) {
while (!operators.empty() && priority(operators.top()) >= priority(expression[i])) {
char op = operators.top();
operators.pop();
double a = values.top();
values.pop();
double b = values.top();
values.pop();
values.push(apply_operator(op, b, a));
}
operators.push(expression[i]);
} else {
cout << "Invalid character in expression: " << expression[i] << endl;
return 0;
}
}
while (!operators.empty()) {
char op = operators.top();
operators.pop();
double a = values.top();
values.pop();
double b = values.top();
values.pop();
values.push(apply_operator(op, b, a));
}
return values.top();
}
int main() {
ifstream config_file("config.txt");
if (!config_file.is_open()) {
cout << "Error opening config file." << endl;
return 0;
}
string expression;
getline(config_file, expression);
config_file.close();
double result = calculate(expression);
cout << "Result: " << result << endl;
return 0;
}
Пример файла конфигурации "config.txt":
2 + 3 * (4 - 1) -5 * (3 + 2) 10 / 2 - 3 * (7 - 1) / 2
