Cod sursa(job #2348215)

Utilizator vladcoroian2001Vlad Coroian vladcoroian2001 Data 19 februarie 2019 15:13:40
Problema Evaluarea unei expresii Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <stack>
#include <map>
using namespace std;
ifstream fi("evaluare.in");
ofstream fo("evaluare.out");
stack <int> nr;
stack <char> op;
map <char ,int> pr;
string s;
int a,b,x,ok;
int main()
{
    fi>>s;
    s="("+s;
    s=s+")";
    pr['+']=1; pr['-']=2; pr['*']=3; pr['/']=4;
    pr[')']=0;
    pr['(']=0;
    op.push('(');
    for(int i=1;i<s.size();i++)
    {
        x=0; ok=0;
        while(i<s.size() && s[i]>='0' && s[i]<='9')
        {
            ok=1;
            x=x*10+(s[i]-'0');
            i++;
        }
        if(ok)
        {
            nr.push(x);
            i--;
            continue;
        }
        while(op.top()!='(' && s[i]!='(' && pr[s[i]]<pr[op.top()])
        {
            a=nr.top(); nr.pop();
            b=nr.top(); nr.pop();
            if(op.top()=='+') nr.push(a+b);
            if(op.top()=='-') nr.push(b-a);
            if(op.top()=='*') nr.push(a*b);
            if(op.top()=='/') nr.push(b/a);
            op.pop();
        }
        if(s[i]==')') op.pop();
        else op.push(s[i]);
    }
    fo<<nr.top();
    fi.close();
    fo.close();
    return 0;
}