Pagini recente » Cod sursa (job #2400200) | Cod sursa (job #1532533) | Cod sursa (job #1515750) | Cod sursa (job #2394206) | Cod sursa (job #3214874)
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
#include <stack>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
const int NMAX = 100000;
char s[NMAX + 5];
stack<char> op, polo;
stack<int> r;
int ord(char o){
switch(o){
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
default:
return 0;
}
}
int operatie(int a, int b, char op){
switch(op){
case '+':
return b + a;
case '-':
return b - a;
case '*':
return b * a;
case '/':
return b / a;
default:
return -1;
}
}
int main()
{
int len, i, nr, num, a, b;
fin.getline(s, NMAX + 5);
len = strlen(s);
for(i = 0; i < len; ++i){
if(isdigit(s[i])){
while(isdigit(s[i])){
polo.push(s[i]);
i++;
}
polo.push(' ');
i--;
continue;
}
if(s[i] == '('){
op.push(s[i]);
continue;
}
if(s[i] == ')'){
while(op.top() != '('){
polo.push(op.top());
op.pop();
}
op.pop();
continue;
}
if(op.empty() || op.top() == '(' || ord(s[i]) > ord(op.top())){
op.push(s[i]);
}
else{
while(!op.empty() && ord(s[i]) <= ord(op.top())){
polo.push(op.top());
op.pop();
}
op.push(s[i]);
}
}
while(!op.empty()){
polo.push(op.top());
op.pop();
}
while(!polo.empty()){
op.push(polo.top());
polo.pop();
}
num = 0;
while(!op.empty()){
if(isdigit(op.top())){
num *= 10;
num += op.top() - '0';
op.pop();
}
else if(op.top() == ' '){
r.push(num);
num = 0;
op.pop();
}
else{
a = r.top();
r.pop();
b = r.top();
r.pop();
r.push(operatie(a, b, op.top()));
op.pop();
}
}
fout << r.top();
fin.close();
fout.close();
return 0;
}