Cod sursa(job #1619928)

Utilizator Wh1plashOvidiu Taralesca Wh1plash Data 28 februarie 2016 19:51:32
Problema Evaluarea unei expresii Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <stack>
#include <string>
#include <fstream>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
string s;
int i;
int prio[1001];
stack<int> st ;
stack<char> op ;

void eval()
{
    int n=0;
    while(isdigit(s[i]))
    {
        n = n*10 + (s[i]-'0');
        i++;
    }
    i--;
    st.push(n);
   // cout<<n<<' ';
}
void calc()
{
    int x=st.top(); st.pop();
    int y=st.top(); st.pop();
    char c = op.top();
    op.pop();
    if(c=='+') st.push(y+x);
    if(c=='-') st.push(y-x);
    if(c=='/') st.push(y/x);
    if(c=='*') st.push(y*x);

}
int main()
{
    in>>s;


    prio['-']=prio['+']=1;
    prio['*']=prio['/']=2;

    for(;i<(int)s.size();i++)
    {
        if(isdigit(s[i]))
        {
            eval();
        }
        else if(s[i]=='(') op.push('(');
        else if(s[i]==')')
        {
            while(op.top()!='(') calc();
            op.pop(); // scoate ( din stiva
        }
        else
        {
            while(!op.empty() && prio[(int)op.top()]>prio[(int)s[i]])
                calc();
            op.push(s[i]);
        }
    }
    while(!op.empty()) calc();
    out<<st.top();
    return 0;
}