Pagini recente » Cod sursa (job #2421331) | Cod sursa (job #1227259) | Rating Crocodil Deapa (Crocodil_deapa) | Cod sursa (job #1376193) | Cod sursa (job #2247048)
#include <cctype>
#include <fstream>
#include <string>
using namespace std;
int Eval(const string &str, size_t &pos);
int GetNumber(const string &str, size_t &pos)
{
if (str[pos] == '(') {
pos += 1;
auto num = Eval(str, pos);
pos += 1;
return num;
}
auto num = 0;
while (pos < str.size() && isdigit(str[pos])) {
num = num * 10 + str[pos] - '0';
pos += 1;
}
return num;
}
int MultDiv(const string &str, size_t &pos)
{
auto prod = GetNumber(str, pos);
while (pos < str.size() && (str[pos] == '*' || str[pos] == '/')) {
auto is_mult = str[pos] == '*';
pos += 1;
auto other = GetNumber(str, pos);
if (is_mult) {
prod *= other;
} else {
prod /= other;
}
}
return prod;
}
int AddSub(const string &str, size_t &pos)
{
auto sum = MultDiv(str, pos);
while (pos < str.size() && (str[pos] == '+' || str[pos] == '-')) {
auto is_plus = str[pos] == '+';
pos += 1;
auto other = MultDiv(str, pos);
sum += other * (is_plus ? 1 : -1);
}
return sum;
}
int Eval(const string &str, size_t &pos)
{
return AddSub(str, pos);
}
int Eval(const string &str)
{
size_t pos = 0;
return Eval(str, pos);
}
int main()
{
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string str;
getline(fin, str);
auto res = Eval(str);
fout << res << "\n";
return 0;
}