Cod sursa(job #2857176)

Utilizator gabriela.stanStan Luciana-Gabriela gabriela.stan Data 25 februarie 2022 08:34:01
Problema Evaluarea unei expresii Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("evaluare.in");
ofstream g("evaluare.out");

stack <int> nr;
stack <char> op;

char sir[100001];

void eval()
{
    int x=nr.top();
    nr.pop();
    int y=nr.top();
    nr.pop();
    char c;
    c=op.top();
    op.pop();
    cout<<'\n'<<"op: "<<(char)c<<'\n';
    if(c=='+') nr.push(x+y);
    else if(c=='-') nr.push(y-x);
    else if(c=='*') nr.push(y*x);
    else nr.push(y/x);
    cout<<"x="<<x<<'\n'<<"y="<<y<<'\n'<<"nr="<<nr.top()<<'\n'<<'\n';
}

int rez(char s[100005], int k)
{
    int n=k;
    for(int i=0; i<n; i++)
    {
        if(isdigit(s[i]))
        {
            int x=0;
            while(i<n && isdigit(s[i]))
            {
                x=x*10+s[i]-'0';
                i++;
            }
            i--;
            nr.push(x);
            cout<<"x= "<<x<<'\n';
        }
        else if(s[i]=='(') op.push(s[i]);
        else if(s[i]==')' && !op.empty())
        {
            if(op.top()=='(') op.pop();
            else while(!op.empty() && op.top()!='(' && !nr.empty()) eval();
            op.pop();
        }
        else if(op.empty()) op.push(s[i]);
        else if(s[i]=='*')
        {
            while(!op.empty() && op.top()=='/') eval();
            op.push(s[i]);
        }
        else if(s[i]=='/')
        {
            while(!op.empty() && (op.top()=='*' || op.top()=='/')) eval();
            op.push(s[i]);
        }
        else if(s[i]=='-')
        {
            while(!op.empty() && (op.top()=='*' || op.top()=='/' || op.top()=='-')) eval();
            op.push(s[i]);
        }
        else if(s[i]=='+')
        {
            while(!op.empty() && (op.top()=='*' || op.top()=='/' || op.top()=='-')) eval();
            op.push(s[i]);
        }
    }
    while(!op.empty()) eval();
    return nr.top();
}

int main()
{
    f>>sir;
    g<<rez(sir, strlen(sir));
    return 0;
}