Cod sursa(job #2918401)

Utilizator Tudose_StefanTudose Alexandru Stefan Tudose_Stefan Data 11 august 2022 13:59:36
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.53 kb
#include <iostream>
#include <stack>
#include <cstring>

using namespace std;

string infix, polish, nrr;
int lung, i, nr1, nr2;
bool startNr;
char *p;

int preced(char c){
    if (c == '+' || c == '-')
        return 1;
    if (c == '*' || c == '/')
        return 2;
    if (c == '(')
        return 0;
}

stack <char> stk;
stack <int> stkNr;

int main()
{
    cin >> infix;
    lung = infix.length();
    startNr = false;
    for (i = 0; i < lung; ++i)
    {
        ///cout << "am ajuns la pasul " << i << '\n';
        if (infix[i] >= 48 && infix[i] <= 58){
            if (startNr == false){
                nrr = "";
                nrr += infix[i];
                startNr = true;
            }
            else
                nrr += infix[i];
        }
        else{
            if (startNr){
                startNr = false;
                polish += nrr;
                polish += ' ';
            }
            if (stk.empty())
                stk.push(infix[i]);
            else if (infix[i] != ')'){
                if (preced(infix[i]) > preced(stk.top()) || infix[i] == '(')
                    stk.push(infix[i]);
                else{
                    polish += stk.top();
                    polish += ' ';
                    stk.pop();
                    stk.push(infix[i]);
                }
            }
            else{
                while (stk.top() != '('){
                    polish += stk.top();
                    polish += ' ';
                    stk.pop();
                }
                //cout << "test1\n";
                stk.pop();
                //cout << "test2\n";
            }
        }
    }
    if (startNr){
        polish += nrr;
        polish += ' ';
    }
    //cout << "am ajuns";
    while (!stk.empty()){
        polish += stk.top();
        polish += ' ';
        stk.pop();
    }
    char * dup = strdup(polish.c_str());

    p = strtok(dup, " ");
    while (p != NULL){
        if (p[0]>= 48 && p[0] <= 58)
            stkNr.push(atoi(p));
        else{
            nr1 = stkNr.top();
            stkNr.pop();
            nr2 = stkNr.top();
            stkNr.pop();
            if (p[0] == '+')
                stkNr.push(nr1+nr2);
            if (p[0] == '*')
                stkNr.push(nr1*nr2);
            if(p[0] == '/')
                stkNr.push(nr2/nr1);
            if(p[0] == '-')
                stkNr.push(nr2-nr1);
        }
        p = strtok(NULL, " ");
    }
    cout << stkNr.top();


    return 0;
}