Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ArithmeticExpr.cpp: определяет точку входа для консольного приложения.
- //
- #include "stdafx.h"
- #include <iostream>
- #include <string>
- #include <vector>
- using namespace std;
- char signs[] = { '*', '/', '+', '-', '=' };
- bool isOperator(char symb)
- {
- if (symb == '+' || symb == '-' || symb == '*' || symb == '/' || symb == '(' || symb == ')')
- return true;
- else
- return false;
- }
- void reverse(string& input)
- {
- string output;
- for (int i = input.length() - 1; i > -1; i--)
- output = output + input[i];
- input = output;
- }
- int getPrcd(char symb)
- {
- if (symb == '*' || symb == '/')
- return 4;
- if (symb == '+' || symb == '-')
- return 2;
- if (symb == '(' || symb == ')' || symb == '#')
- return 1;
- }
- void infixToPrefix(string infix, string& prefix)
- {
- int i, j = 0;
- char symb;
- vector<char> opArray;
- opArray.push_back('#');
- reverse(infix);
- for (i = 0; i < infix.length(); i++)
- {
- symb = infix[i];
- if (isOperator(symb) == 0)
- {
- prefix = prefix + symb;
- j++;
- }
- else
- {
- if (symb == ')')
- {
- opArray.push_back(symb);
- }
- else if (symb == '(')
- {
- while (opArray.back() != ')')
- {
- prefix = prefix + opArray.back();
- opArray.pop_back();
- j++;
- }
- opArray.pop_back();
- }
- else
- {
- if (getPrcd(opArray.back()) <= getPrcd(symb))
- {
- opArray.push_back(symb);
- }
- else
- {
- while (getPrcd(opArray.back()) >= getPrcd(symb))
- {
- prefix = prefix + opArray.back();
- opArray.pop_back();
- j++;
- }
- opArray.push_back(symb);
- }
- }
- }
- }
- while (opArray.back() != '#')
- {
- prefix = prefix + opArray.back();
- opArray.pop_back();
- j++;
- }
- }
- void genCode(string txt)
- {
- string code;
- string leftop;
- string rightop;
- string curCode;
- string op;
- int i = 0;
- while (txt[i] != '\0')
- {
- if (txt[i] == '=')
- {
- code = txt[i + 1];
- code = "mov " + code + ",ax\n";
- }
- else if (isOperator(txt[i]))
- {
- if (!isOperator(txt[i + 1]) && !isOperator(txt[i + 2]))
- {
- leftop = txt[i + 1];
- rightop = txt[i + 2];
- switch (txt[i])
- {
- case '+': op = "add "; break;
- case '-': op = "sub "; break;
- case '*': op = "mul "; break;
- case '/': op = "div "; break;
- default:
- break;
- }
- curCode = "mov eax, " + leftop + "\n" + op + "eax, " + rightop;
- code = curCode + "\n" + code;
- }
- if (isOperator(txt[i + 1]) && !isOperator(txt[i + 2]))
- {
- }
- }
- }
- cout << code;
- }
- int main()
- {
- string input;
- string output;
- cin >> input;
- infixToPrefix(input, output);
- reverse(output);
- output = "=A" + output;
- cout << output << endl;
- genCode(output);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment