Cod sursa(job #3372272)

Utilizator alexm749Musat Alexandru Nicolae alexm749 Data 2 noiembrie 2026 22:10:18
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.96 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <cstring>

using namespace std;

ifstream f("evaluare.in");

ofstream g("evaluare.out");

int prioritate(char c)
{
    if(c=='+'||c=='-')return 1;
    if(c=='*'||c=='/')return 2;
    return 0;
}

void parsing(char t[], char s[])
{
    int k=0;
    stack<char> st;
    for(int i=0;s[i];i++)
    {
        if(isdigit(s[i]))
        {
            while(s[i]&&isdigit(s[i]))
            {
                t[k++]=s[i];
                i++;
            }
            t[k++]=',';
            i--;
        }
        else if(s[i]=='(')st.push('(');
        else if(s[i]==')')
        {
            while(st.top()!='(')
            {
                t[k++]=st.top();
                st.pop();
            }
            st.pop();
        }
        else
        {
            while(!st.empty()&&prioritate(st.top())>=prioritate(s[i]))
            {
                t[k++]=st.top();
                st.pop();
            }
            st.push(s[i]);
        }
    }
    while(!st.empty())
    {
        t[k++]=st.top();
        st.pop();
    }
    t[k]='\0';
}

int eval(char s[])
{
    stack<int> st;
    for(int i=0;s[i];i++)
    {
        if(isdigit(s[i]))
        {
            int nr=0;
            while(isdigit(s[i]))
            {
                nr=nr*10+(int)(s[i]-'0');
                i++;
            }
            st.push(nr);
        }
        else
        {
            int a,b;
            a=st.top();
            st.pop();
            b=st.top();
            st.pop();
            if(s[i]=='+')st.push(b+a);
            else if(s[i]=='-')st.push(b-a);
            else if(s[i]=='*')st.push(b*a);
            else st.push(b/a);
        }
    }
    int rez=st.top();
    st.pop();
    return rez;
}

int main()
{
    char s[100001],t[200001];
    f.getline(s,100001);
    parsing(t,s);
    //cout<<t;
    g<<eval(t);
    return 0;
}