Pagini recente » Cod sursa (job #3038074) | Cod sursa (job #3249368) | Cod sursa (job #2118204) | Cod sursa (job #2536999) | Cod sursa (job #2223855)
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
const string IN_FILE = "evaluare.in";
const string OUT_FILE = "evaluare.out";
class Evaluator {
public:
Evaluator(const string expression) : exp(expression) {}
int evaluate() {
p = 0;
return expression();
}
private:
string exp;
int p;
int expression() {
int value = term();
while (p < int(exp.length()) && (exp[p] == '+' || exp[p] == '-')) {
value = exp[p++] == '+' ? value + term() : value - term();
}
return value;
}
int term() {
int value = factor();
while (p < int(exp.length()) && (exp[p] == '*' || exp[p] == '/')) {
value = exp[p++] == '*' ? value * factor() : value / factor();
}
return value;
}
int factor() {
if (exp[p] == '(') {
p++;
const int value = expression();
p++;
return value;
}
int sign = 1;
if (exp[p] == '-') {
sign = -1;
p++;
}
int value = 0;
while (p < int(exp.length()) && isdigit(exp[p])) {
value = value * 10 + exp[p++] - '0';
}
return sign * value;
}
};
string readInput() {
ifstream in(IN_FILE);
string exp;
in >> exp;
in.close();
return exp;
}
void writeOutput(const int result) {
ofstream out(OUT_FILE);
out << result << "\n";
out.close();
}
int main() {
const string exp = readInput();
const int result = Evaluator(exp).evaluate();
writeOutput(result);
return 0;
}