Pagini recente » Cod sursa (job #102694) | Cod sursa (job #3342504) | Cod sursa (job #3311450) | Cod sursa (job #3349817) | Cod sursa (job #3346610)
#include <bits/stdc++.h>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
string s;
stack<char> op;
stack<int> num;
bool calc(int i) {
if (s[i]==')') {
return true;
}
if (op.empty()) {
return false;
}
if ((op.top()=='*' || op.top()=='/') && (s[i]=='+' || s[i]=='-')) {
return true;
}
return false;
}
void ex() {
while (!op.empty() && op.top()!='(') {
int x = num.top();
num.pop();
if (op.top()=='+') {
num.top()+=x;
}
else if (op.top()=='-') {
num.top()-=x;
}
else if (op.top()=='*') {
num.top()*=x;
}
else if (op.top()=='/') {
num.top()/=x;
}
op.pop();
}
if (!op.empty())
op.pop();
}
int eval() {
int n=0;
bool nou=true;
for (int i=0;i<s.size();i++) {
if (!(s[i]-'0'>=0 && s[i]-'0'<=9)) {
if (nou==false) {
num.push(n);
n=0;
nou=true;
}
if (calc(i)==true) {
ex();
}
if (s[i]!=')')
op.push(s[i]);
}
else {
n=n*10+s[i]-'0';
nou=false;
}
}
num.push(n);
ex();
return num.top();
}
int main(){
in>>s;
out<<eval();
return 0;
}