Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Вычисление символьных выражений
- 1. Преобразование строкового представления в последовательность токенов
- 2.0 * abc+sin((a-b+c)^(x/y - abc))
- Синт. элементы : 2.0 , *, abc, +, sin, (,...)
- name = abc
- type = переменная
- 2. Преобразование посл.токенов в постфиксную запись
- 2.0 * ab - с + xy / abc - ^ sin +
- map<string,int> priority;
- 3.1 Считывание данных из потока
- первая строка - выражение
- последующая - имя переменной = значение
- и так много раз
- переменная = значение
- 3.2 Реализация операций
- map<string,double(*)(stack<double> &)> functions;
- //хранит указатели на функцию
- если открывающая скобка - функция
- иначе - переменная
- токен закнчивается на знаке операций, скобке или пробеле (терм.символ)
- isdigit - символ
- isalpha - буква
- */
- #include "stdafx.h"
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <cstdio>
- #include <vector>
- #include <stack>
- #include <algorithm>
- #include <map>
- #include <cctype>
- using namespace std;
- enum tokentype { ttconst, ttvar, ttopbr, ttclbr, ttfun, ttop };
- struct token
- {
- string name;
- tokentype type; // перечисление
- token(string n = " ", tokentype t = ttop)
- {
- name = n;
- type = t;
- }
- token(char n = ' ', tokentype t = ttop)
- {
- name = n;
- type = t;
- }
- void printToken()
- {
- cout << name.c_str() << " " << type;
- cout << endl;
- }
- };
- string termsymbol = "+-*/^()[]%!&|";
- bool istermsymbol(char c)
- {
- return termsymbol.find(c) != -1;
- }
- tokentype ExpressionFunctionOrVariable(string s)
- {
- if (s.find("(") != -1) //(s == "sin" || s == "cos" || s == "tan" || s == "arcsin" || s == "arccos" || s == "arctan")
- return ttfun;
- return ttvar;
- }
- bool WhetherAStringIsANumber(string s)
- {
- for (int i = 0; i < s.size(); i++)
- if (s[i] != '.' && isdigit(s[i]) == false)
- return false;
- return true;
- }
- vector<token> BuildToken(string s) // "sin(x)+7*abc^13-9.3*acrtg(1)"
- {
- vector<token> TokenVec;
- string tmp = "";
- for (int i =0; i< s.size(); i++)
- {
- if (istermsymbol(s[i]))
- {
- if (WhetherAStringIsANumber(tmp) && tmp != "")
- TokenVec.push_back(token(tmp, ttconst));
- else if (tmp != "")
- TokenVec.push_back(token(tmp, ExpressionFunctionOrVariable(tmp+s[i])));
- switch (s[i])
- {
- case '(':
- TokenVec.push_back(token(s[i], ttopbr));
- break;
- case ')':
- TokenVec.push_back(token(s[i], ttclbr));
- break;
- default:
- TokenVec.push_back(token(s[i], ttop));
- break;
- }
- tmp = "";
- }
- else
- {
- tmp += s[i];
- if (tmp.find(" ") != -1)
- tmp.erase (tmp.find(" "), 1);
- }
- }
- return TokenVec;
- }
- void Postfix(vector<token> Tk)
- {
- }
- double pop(stack<double> &s)
- {
- double res = s.top();
- s.pop();
- return res;
- }
- map<string, int> priority; // приоритеты
- void BuildPriorityMap()
- {
- priority["sin"] = 10;
- //дописать приоритет
- }
- //тут должен быть ввод из файла
- /*double op_plus(stack<double> &S)
- {
- return pop(S) + pop(S);
- }*/
- map<string, double(*)(stack<double> &)> functions;
- void BuildFunctionMap()
- {
- functions["+"] = [](stack<double> &s) {return pop(s) + pop(s); };
- functions["*"] = [](stack<double> &s) {return pop(s) * pop(s); }; // лямбда - выражение
- functions["-"] = [](stack<double> &s) {return -pop(s) + pop(s); };
- functions["/"] = [](stack<double> &s) {return pop(s) / pop(s); };
- functions["^"] = [](stack<double> &s) {return pow(pop(s), pop(s)); };
- functions["sin"] = [](stack<double> &s) {return sin(pop(s)); };
- functions["cos"] = [](stack<double> &s) {return cos(pop(s)); };
- //functions["!"] = [&f](stack<double> &s) -> int { return (n) ? pop(s)*f(pop(s) - 1) : 1; };
- //functions["^"] = [](stack<double> &s) {
- // дописать
- }
- map<string, int> variable;
- int main()
- {
- string s;
- string expression;
- ifstream file("test.txt");
- bool key = true;
- while (getline(file, s))
- if (key == true)
- {
- expression = s;
- key = false;
- }
- else
- variable[string(s, 0, s.find("="))] = atoi(string(s, s.find("="), s.size() - 1).c_str()); // записываем значение переменных
- file.close();
- vector<token> T1;
- T1 = BuildToken(expression); // ttconst, ttvar, ttopbr, ttclbr, ttfun, ttop 700+sin(x) + 7 * abc ^ 13 - 9.3*acrtg(1)
- for (int i =0; i<T1.size(); i++)
- {
- T1[i].printToken();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement