Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2018
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.74 KB | None | 0 0
  1. /*Вычисление символьных выражений
  2. 1. Преобразование строкового представления в последовательность токенов
  3. 2.0 * abc+sin((a-b+c)^(x/y - abc))
  4. Синт. элементы : 2.0 , *, abc, +, sin, (,...)
  5. name = abc
  6. type = переменная
  7. 2. Преобразование посл.токенов в постфиксную запись
  8. 2.0 * ab - с + xy / abc - ^ sin +
  9. map<string,int> priority;
  10. 3.1 Считывание данных из потока
  11. первая строка - выражение
  12. последующая - имя переменной = значение
  13. и так много раз
  14. переменная = значение
  15. 3.2 Реализация операций
  16. map<string,double(*)(stack<double> &)> functions;
  17. //хранит указатели на функцию
  18. если открывающая скобка - функция
  19. иначе - переменная
  20. токен закнчивается на знаке операций, скобке или пробеле (терм.символ)
  21. isdigit - символ
  22. isalpha - буква
  23. */
  24.  
  25. #include "stdafx.h"
  26. #include <iostream>
  27. #include <fstream>
  28. #include <string>
  29. #include <cstdio>
  30. #include <vector>
  31. #include <stack>
  32. #include <algorithm>
  33. #include <map>
  34. #include <cctype> 
  35.  
  36. using namespace std;
  37.  
  38. enum tokentype { ttconst, ttvar, ttopbr, ttclbr, ttfun, ttop };
  39. struct token
  40. {
  41. string name;
  42. tokentype type; // перечисление
  43. token(string n = " ", tokentype t = ttop)
  44. {
  45. name = n;
  46. type = t;
  47. }
  48. token(char n = ' ', tokentype t = ttop)
  49. {
  50. name = n;
  51. type = t;
  52. }
  53. void printToken()
  54. {
  55. cout << name.c_str() << " " << type;
  56. cout << endl;
  57. }
  58. };
  59.  
  60. string termsymbol = "+-*/^()[]%!&|";
  61. bool istermsymbol(char c)
  62. {
  63. return termsymbol.find(c) != -1;
  64.  
  65. }
  66.  
  67. tokentype ExpressionFunctionOrVariable(string s)
  68. {
  69. if (s.find("(") != -1) //(s == "sin" || s == "cos" || s == "tan" || s == "arcsin" || s == "arccos" || s == "arctan")
  70. return ttfun;
  71. return ttvar;
  72. }
  73.  
  74. bool WhetherAStringIsANumber(string s)
  75. {
  76.  
  77. for (int i = 0; i < s.size(); i++)
  78. if (s[i] != '.' && isdigit(s[i]) == false)
  79. return false;
  80. return true;
  81. }
  82.  
  83.  
  84. vector<token> BuildToken(string s) // "sin(x)+7*abc^13-9.3*acrtg(1)"
  85. {
  86. vector<token> TokenVec;
  87. string tmp = "";
  88. for (int i =0; i< s.size(); i++)
  89. {
  90. if (istermsymbol(s[i]))
  91. {
  92. if (WhetherAStringIsANumber(tmp) && tmp != "")
  93. TokenVec.push_back(token(tmp, ttconst));
  94. else if (tmp != "")
  95. TokenVec.push_back(token(tmp, ExpressionFunctionOrVariable(tmp+s[i])));
  96. switch (s[i])
  97. {
  98. case '(':
  99. TokenVec.push_back(token(s[i], ttopbr));
  100. break;
  101. case ')':
  102. TokenVec.push_back(token(s[i], ttclbr));
  103. break;
  104. default:
  105. TokenVec.push_back(token(s[i], ttop));
  106. break;
  107. }
  108. tmp = "";
  109.  
  110. }
  111. else
  112. {
  113. tmp += s[i];
  114. if (tmp.find(" ") != -1)
  115. tmp.erase (tmp.find(" "), 1);
  116. }
  117. }
  118. return TokenVec;
  119. }
  120.  
  121. void Postfix(vector<token> Tk)
  122. {
  123.  
  124. }
  125.  
  126. double pop(stack<double> &s)
  127. {
  128. double res = s.top();
  129. s.pop();
  130. return res;
  131. }
  132. map<string, int> priority; // приоритеты
  133.  
  134. void BuildPriorityMap()
  135. {
  136. priority["sin"] = 10;
  137. //дописать приоритет
  138. }
  139. //тут должен быть ввод из файла
  140. /*double op_plus(stack<double> &S)
  141. {
  142. return pop(S) + pop(S);
  143.  
  144. }*/
  145.  
  146. map<string, double(*)(stack<double> &)> functions;
  147. void BuildFunctionMap()
  148. {
  149. functions["+"] = [](stack<double> &s) {return pop(s) + pop(s); };
  150. functions["*"] = [](stack<double> &s) {return pop(s) * pop(s); }; // лямбда - выражение
  151. functions["-"] = [](stack<double> &s) {return -pop(s) + pop(s); };
  152. functions["/"] = [](stack<double> &s) {return pop(s) / pop(s); };
  153. functions["^"] = [](stack<double> &s) {return pow(pop(s), pop(s)); };
  154. functions["sin"] = [](stack<double> &s) {return sin(pop(s)); };
  155. functions["cos"] = [](stack<double> &s) {return cos(pop(s)); };
  156. //functions["!"] = [&f](stack<double> &s) -> int { return (n) ? pop(s)*f(pop(s) - 1) : 1; };
  157. //functions["^"] = [](stack<double> &s) {
  158. // дописать
  159. }
  160.  
  161. map<string, int> variable;
  162.  
  163. int main()
  164. {
  165. string s;
  166. string expression;
  167. ifstream file("test.txt");
  168. bool key = true;
  169. while (getline(file, s))
  170. if (key == true)
  171. {
  172. expression = s;
  173. key = false;
  174. }
  175. else
  176. variable[string(s, 0, s.find("="))] = atoi(string(s, s.find("="), s.size() - 1).c_str()); // записываем значение переменных
  177.  
  178. file.close();
  179.  
  180.  
  181. vector<token> T1;
  182. T1 = BuildToken(expression); // ttconst, ttvar, ttopbr, ttclbr, ttfun, ttop 700+sin(x) + 7 * abc ^ 13 - 9.3*acrtg(1)
  183. for (int i =0; i<T1.size(); i++)
  184. {
  185. T1[i].printToken();
  186. }
  187. return 0;
  188. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement