Pagini recente » Cod sursa (job #1257825) | Cod sursa (job #2334100) | Cod sursa (job #1087191) | Cod sursa (job #2780025) | Cod sursa (job #3256657)
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <stack>
using namespace std;
ifstream f ("evaluare.in");
ofstream g ("evaluare.out");
string s;
int ptr;
char getSgn ()
{
if (s[ptr]=='+' || s[ptr]=='-' || s[ptr]=='/' || s[ptr]=='*')
{
char ret=s[ptr];
ptr++;
return ret;
}
return '+';
}
int getNr ()
{
int nr=0;
while (ptr<s.size() && isdigit (s[ptr]))
{
nr=nr*10+s[ptr++]-'0';
}
return nr;
}
int rec ()
{
stack <int> stiva;
while (ptr<s.size() && s[ptr]!=')')
{
int sgn='+';
sgn=getSgn ();
int nr=0;
if (s[ptr]=='(')
{
ptr++;
nr=rec();
}
else
{
nr=getNr ();
}
if (sgn=='*')
{
int tp=stiva.top();
stiva.pop();
stiva.push (tp*nr);
}
else if (sgn=='/')
{
int tp=stiva.top();
stiva.pop();
stiva.push (tp/nr);
}
else
{
if (sgn=='-')
{
nr=-nr;
}
stiva.push (nr);
}
}
if (s[ptr]==')')
{
ptr++;
}
int ret=0;
while (!stiva.empty())
{
ret+=stiva.top();
stiva.pop();
}
return ret;
}
int main()
{
f >> s;
g << rec ();
return 0;
}