Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <algorithm>
- #include <unordered_map>
- #include <stack>
- using namespace std;
- bool isOperator(char c)
- {
- return c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')';
- }
- string convert(string expr)
- {
- stack<char> temp;
- string result = "";
- expr.erase(remove_if(expr.begin(), expr.end(), isspace), expr.end());
- for (char ch : expr)
- {
- switch (ch)
- {
- case '+':
- case '-':
- {
- while (!temp.empty() && temp.top() != '(')
- {
- result.push_back(temp.top());
- temp.pop();
- }
- temp.push(ch);
- break;
- }
- case '/':
- case '*':
- {
- while (!temp.empty() && temp.top() != '(' && temp.top() != '+' && temp.top() != '-') {
- result.push_back(temp.top());
- temp.pop();
- }
- temp.push(ch);
- break;
- }
- case '(': {
- temp.push('(');
- break;
- }
- case ')':
- {
- while (!temp.empty())
- {
- char t = temp.top();
- temp.pop();
- if (t != '(')
- {
- result.push_back(t);
- }
- else break;
- }
- break;
- }
- default:
- result += ch;
- }
- }
- while (!temp.empty())
- {
- result.push_back(temp.top());
- temp.pop();
- }
- return result;
- }
- double eval(string expression, unordered_map<char, double> vars)
- {
- stack<double> values;
- for (char c : expression)
- {
- if (!isOperator(c))
- {
- values.push(vars[c]);
- }
- else
- {
- double v1 = values.top();
- values.pop();
- double v2 = values.top();
- values.pop();
- switch (c)
- {
- case '+': values.push(v2 + v1); break;
- case '-': values.push(v2 - v1); break;
- case '*': values.push(v2 * v1); break;
- case '/': values.push(v2 / v1); break;
- default:
- cerr << "Error!";
- };
- }
- }
- return values.top();
- }
- int main()
- {
- unordered_map<char, double> vars;
- string input; // test = "( 8 + 2 * 5 ) / ( 1 + 3 * 2 - 4 )";
- cout << "Enter string: " << endl;
- cin >> input;
- for (char c = 'a'; c <= 'e'; c++)
- {
- cout << c << "=";
- cin >> vars[c];
- }
- string rpn = convert(input);
- std::cout << rpn << endl;
- std::cout << eval(rpn, vars);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement