Cod sursa(job #2760755)

Utilizator SurduTonySurdu Tony SurduTony Data 28 iunie 2021 22:15:28
Problema Evaluarea unei expresii Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.4 kb
#include <iostream>
#include <string.h>
#include <fstream>
#include <stack>
using namespace std;

string formaPoloneza(string s) {
    string pol;
    stack<char> myStack;

    for (char c : s) {
        if (c >= '0' && c <= '9') {
            pol.push_back(c);
        }
        else if (c == '*' || c == '/') {
            pol.push_back(' ');
            while (!myStack.empty() && (myStack.top() == '*' || myStack.top() == '/')) {
                pol.push_back(myStack.top());
                myStack.pop();
            }
            myStack.push(c);
        }
        else if (c == '+' || c == '-') {
            pol.push_back(' ');
            while (!myStack.empty() && myStack.top() != '(') { 
                pol.push_back(myStack.top());
                myStack.pop();
            }
            myStack.push(c);
        }
        else if (c == ')') {
            pol.push_back(' ');
            while (!myStack.empty() && myStack.top() != '(') {
                pol.push_back(myStack.top());
                myStack.pop();
            }
            myStack.pop();
        }
        else if (c == '(') {
            myStack.push('(');
        }
    }

    pol.push_back(' ');
    while (!myStack.empty()) {
        pol.push_back(myStack.top());
        myStack.pop();
    }

    return pol;
}

float calculate(float a, float b, char op) {
    switch (op) {
        case '+':
            return a + b;
        case '-':
            return a - b;
        case '*':
            return a * b;
        case '/':
            return a / b;
    }
    return 0;
}

float evaluareExpresie(string s) {
    stack<float> myStack;
    string num;

    for (char c : s) {
        if (c >= '0' && c <= '9') {
            num.push_back(c);
        }
        else {
            if (num.size() > 0) {
                myStack.push(stoi(num));
                num.erase();
            }
            if (c != ' ') {
                float a = myStack.top();
                myStack.pop();
                float b = myStack.top();
                myStack.pop();

                myStack.push(calculate(b, a, c));
            }
        }
    }

    return myStack.top();
}

int main() 
{
    ifstream fin("evaluare.in");
    ofstream fout("evaluare.out");
    
    string s;
    fin >> s;

    s = formaPoloneza(s);
    fout << evaluareExpresie(s);
  
    return 0;
}