Pagini recente » Cod sursa (job #2784441) | Cod sursa (job #1801162) | Cod sursa (job #1105298) | Cod sursa (job #317249) | Cod sursa (job #1310295)
#include <fstream>
#include <string>
#include <sstream>
#include <stack>
inline char prec(char c){ switch(c){
case '+': case '-': return 1;
case '*': case '/': return 2;
default: return 0;
} }
std::stack<int> num;
inline void calc(char c){
int a=num.top(); num.pop();
int b=num.top(); num.pop();
switch(c){
case '+': num.push(a+b); break;
case '-': num.push(b-a); break;
case '*': num.push(a*b); break;
case '/': num.push(b/a); break;
}
}
int main(){
std::ifstream fin("evaluare.in");
std::ofstream fout("evaluare.out");
std::string s; fin>>s;
std::istringstream in(s);
std::stack<char> op;
char c;
bool next_neg=false;
bool prev_nr_rp=false; //previous was number or right parantheses so we don't treat - as unary
while(in.get(c)){
if(c>='0'&&c<='9'){
in.putback(c);
int value; in>>value;
num.push(next_neg?-value:value);
prev_nr_rp=true;
next_neg=false;
}
else if(c=='+' || c=='-' || c=='*' || c=='/'){
if(c=='-'&&(!prev_nr_rp)) next_neg=true;
else if(c!='+'||prev_nr_rp){
while( !op.empty() && op.top()!='(' && prec(c)<=prec(op.top()) ){
calc(op.top());
op.pop();
}
op.push(c);
}
prev_nr_rp=false;
}
else if(c=='('){
op.push('(');
prev_nr_rp=false;
}
else if(c==')'){
while(op.top()!='('){ calc(op.top()); op.pop(); }
op.pop();
prev_nr_rp=true;
}
}
while(!op.empty()){ calc(op.top()); op.pop(); }
fout<<num.top()<<'\n';
}