Cod sursa(job #2964675)

Utilizator Alex_DumitrascuAlex Dumitrascu Alex_Dumitrascu Data 13 ianuarie 2023 17:00:19
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include <iostream>
#include <stack>
#include <cstdio>
using namespace std;
FILE *fin=fopen("evaluare.in", "r");
FILE *fout=fopen("evaluare.out", "w");
stack<char> ops;
stack<int> vals;
int importance(char op)
{
    if (op=='*'||op=='/') return 2;
    if (op=='+'||op=='-') return 1;
    return 0;
}
int apply_operation(int a, int b, char c)
{
    switch (c) {
        case '+': return a+b;
        case '-': return a-b;
        case '*': return a*b;
        case '/': return a/b;
    }
}
void doTheMath()
{
    int val2=vals.top();
    vals.pop();
    int val1=vals.top();
    vals.pop();
    char op=ops.top();
    ops.pop();
    vals.push(apply_operation(val1, val2, op));
}
int eval(char *tokens)
{
    for (int i=0; tokens[i]!='\0'; i++) {
        if (tokens[i]==' ') continue;
        else if (tokens[i]=='(') {
            ops.push(tokens[i]);
        }
        else if (isdigit(tokens[i])) {
            int value=0;
            while (tokens[i]!='\0'&&isdigit(tokens[i])) {
                int digit=tokens[i]-'0';
                value=value*10+digit;
                i++;
            }
            vals.push(value);
            i--;
        }
        else if (tokens[i]==')') {
            while (!ops.empty()&&ops.top()!='(') {
                doTheMath();
            }
            if (!ops.empty())
                ops.pop();
        }
        else { ///token is an operator
            while(!ops.empty()&&importance(ops.top())>=importance(tokens[i])) {
                doTheMath();
            }
            ops.push(tokens[i]);
        }
    }
    while (!ops.empty()&&vals.size()>1) {
        doTheMath();
    }
    return vals.top();
}
int main()
{
    char tokens[100005];
    fgets(tokens, sizeof(tokens), fin);
    int rezult=eval(tokens);
    fprintf(fout, "%d", rezult);
    return 0;
}