Cod sursa(job #3346603)

Utilizator dargrigaDarius Griga dargriga Data 14 martie 2026 15:51:13
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
string s;
stack<char> op;
stack <int> nr;
int i=0;
int calc()
{
    r=nr.top;
    nr.pop();
    while(!op.empty())
    {
        while(op.top()=='('||op.top==')')
            op.pop();
        char oper=op.top();
        if(oper=='*')
            r*=nr.top();
        else if(oper=='/')
            r/=nr.top();
        else if(oper=='+')
            r+=nr.top();
        else if(oper=='-')
            r-=nr.top();
        nr.pop();
        oper.pop();
    }
    return r;
}
void getnr()
{
    int r=0;
    while(s[i]>='0'&&s[i]<='9')
        r*=10, r+=s[i], i++;
    nr.push(r);
}

int main()
{
    f >> s;
    int lastop=0;
    op.push('+');
    nr.push(0);
    while(i<s.size())
    {
        if(s[i]>='0'&&s[i]<='9')
            getnr();
        else
        {
            if((s[i]=='*'||s[i]=='/')&&(op.top()=='+'||op.top()=='-'))
            {
                i=lastop-1;
                op.pop();
                nr.pop();
                nr.push(calc);
            }
            else
            {
                op.push(s[i]);
            }
            if(s[i]==')')
                calc();
            lastop=i;
        }
    }
    g << nr.top();
    return 0;
}