Pagini recente » Cod sursa (job #3267300) | Cod sursa (job #2897149) | Cod sursa (job #2535668) | Cod sursa (job #2768280) | Cod sursa (job #2922628)
#include <string>
#include <fstream>
using namespace std;
ifstream cin("evaluare.in");
ofstream cout("evaluare.out");
string operations = "+-*/";
string trimBraces(string s){
if(s.length() < 5) return s;
if((s[0]) == '(' && s[s.length() - 1] == ')'){
return s.substr(1, s.length()-1);
}
return s;
}
int eval(string s) {
int nested = 0;
int currOp = 10, currOpIndex;
for(int i=0; i<s.length(); i++) {
char c = s[i];
if(c == '(') {
nested++;
continue;
} else if(c == ')') {
nested--;
continue;
}
if(nested == 0){
int found = operations.find(c);
if(found != string::npos){
if(found < currOp){
currOp = found;
currOpIndex = i;
};
}
}
}
if(currOp == 10){
return stoi(s);
}
string lhs = trimBraces(s.substr(0, currOpIndex));
string rhs = trimBraces(s.substr(currOpIndex + 1, s.length()));
if(currOp == 0){
return eval(lhs) + eval(rhs);
}
if(currOp == 1){
return eval(lhs) - eval(rhs);
}
if(currOp == 2){
return eval(lhs) * eval(rhs);
}
if(currOp == 3){
return eval(lhs) / eval(rhs);
}
}
int main()
{
string a;
cin>>a;
cout<<eval(a);
return 0;
}