Pagini recente » Cod sursa (job #407978) | Cod sursa (job #1531286) | Cod sursa (job #1429532) | Cod sursa (job #7055) | Cod sursa (job #2964675)
#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;
}