Cod sursa(job #1759638)

Utilizator ghost24ghost ghost ghost24 Data 19 septembrie 2016 17:31:50
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include<iostream>
#include<fstream>
#include<string>
#include<stack>
#include<cctype>

using namespace std;
fstream fin("evaluare.in",ios::in),fout("evaluare.out",ios::out);
int val[200];
string s;
stack<int> nr;
stack<char> op;
char c;

void rezolvare();
int digit(int& poz);
void evaluare();

int main()
{
    val['(']=0;
    val[')']=0;
    val['+']=1;
    val['-']=1;
    val['*']=2;
    val['/']=2;
    fin>>s;
    rezolvare();
}
void evaluare()
{
    int a,b;
    b=nr.top();nr.pop();
    a=nr.top();nr.pop();
    c=op.top();op.pop();
    if(c=='+') nr.push(a+b);
    if(c=='-') nr.push(a-b);
    if(c=='/') nr.push(a/b);
    if(c=='*') nr.push(a*b);
}
int digit(int& i)
{
    int nr=0;
    for( ;i<s.size() && isdigit(s[i]);i++) nr=nr*10+s[i]-'0';
    i--;
    return nr;
}
void rezolvare()
{
    int i;
    for(i=0;i<s.size();i++)
    {
        if(isdigit(s[i]))
        {
            nr.push(digit(i));
        }
        else
        {
            if(s[i]=='(')
            {
                op.push(s[i]);
            }
            else
            {
                if(s[i]==')')
                {
                    while(op.empty()==0 && op.top()!='(') evaluare();
                    if(op.empty()==0 && op.top()=='(') op.pop();
                }
                else
                {
                    while(op.empty()==0 && val[op.top()]>=val[s[i]]) evaluare();
                    op.push(s[i]);
                }
            }
        }
    }
    while(op.empty()==0) evaluare();
    fout<<nr.top()<<"\n";
}