Pagini recente » Cod sursa (job #3294263) | Cod sursa (job #372357) | Cod sursa (job #3300547) | Cod sursa (job #2908845) | Cod sursa (job #806964)
Cod sursa(job #806964)
#include <string>
#include <cstdlib>
#include <fstream>
#define ERROR -(1 << 30)
using namespace std;
string exp;
string::const_iterator it, iend;
const string opLevel[] = {"+-", "*/", "^"};
inline int eval(char op, int a, int b)
{
switch(op)
{
case '+' : return a+b;
case '-' : return a-b;
case '*' : return a*b;
case '/' : return a/b;
default : return ERROR;
}
}
int eval(int level)
{
int x;
if(2 == level)
{
if('(' == *it)
{
++it;
x = eval(0);
++it;
}
else for(x = 0; it < iend && *it >= '0' && *it <= '9'; ++it)
{
x = x*10 + *it - '0';
}
}
else for(x = eval(level+1); it < iend && string::npos != opLevel[level].find(*it);)
{
char op = *(it++);
x = eval(op, x, eval(level+1));
}
return x;
}
int main()
{
ifstream in("evaluare.in");
ofstream out("evaluare.out");
getline(in, exp);
it = exp.begin(), iend = exp.end();
out << eval(0) << '\n';
return EXIT_SUCCESS;
}