Pagini recente » Cod sursa (job #2311084) | Cod sursa (job #1975302) | Cod sursa (job #182165) | Cod sursa (job #2622259) | Cod sursa (job #1484270)
#include<fstream>
#include<stack>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string s;
stack < int > nums;
stack < char > ops;
void operation(){
char op = ops.top(); ops.pop();
int b = nums.top(); nums.pop();
int a = nums.top(); nums.pop();
if(op == '+') nums.push(a + b);
if(op == '-') nums.push(a - b);
if(op == '*') nums.push(a * b);
if(op == '/') nums.push(a / b);
}
inline int priority(char c){
if(c == '+' || c == '-') return 1;
if(c == '*' || c == '/') return 2;
return 0;
}
void solve(){
int p, x;
ops.push('1');
for(int i = 0; i < s.size(); i++){
if(s[i] == '('){
ops.push(s[i]);
} else {
if(s[i] == ')'){
while(ops.top() != '('){
operation();
}
ops.pop();
} else {
p = priority(s[i]);
if(p){
while(priority(ops.top()) >= p){
operation();
}
ops.push(s[i]);
} else {
for(x = 0; isdigit(s[i]); i++){
x = x * 10 + (s[i] - '0');
}
nums.push(x);
i--;
}
}
}
}
while(ops.size() > 1){
operation();
}
}
int main(){
fin >> s;
solve();
fout << nums.top();
return 0;
}