Pagini recente » Cod sursa (job #1023679) | Cod sursa (job #2133286)
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <cctype>
#include <sstream>
#include <queue>
#define pb push_back
using namespace std;
std::ifstream in("evaluare.in");
std::ofstream out("evaluare.out");
bool isOperator(char c)
{
return !isdigit(c) && c !=')' && c!='(';
}
struct op{
int nr;
bool oper;
op(){nr = 0; oper = false;}
op(int n, bool op):nr(n),oper(op){}
};
vector<op> postFix;
int result = 0;
void shutingYard(string I) // infix -> RPN
{
int pre[255]; pre['+'] = 10; pre['-'] = 10; pre['*'] = 11; pre['/'] = 11; pre['('] = -1;pre[')'] = -2;
stack<char> operators;
int i = 0;
char token;
op oper;
while(i< I.size())
{
token = I[i];
if(isdigit(token))
{
string nr("");
nr+=token;
while( i+1 < I.size() && isdigit(I[i+1]))
{
token = I[i+1];
i++;
nr+=I[i];
}
stringstream ss(nr);
ss >> result;
oper.nr = result;
oper.oper = false;
postFix.pb(oper);
}
if(isOperator(token))
{
while ( operators.size()>0 && isOperator(operators.top())&& pre[operators.top()]>=pre[(unsigned int)token])
{
oper.oper = true;
oper.nr = operators.top();
postFix.pb(oper), operators.pop();
}
operators.push(token);
}
if(token =='(')
operators.push(token);
if(token == ')')
{
while(operators.top() != '(')
{
oper.oper = true;
oper.nr = operators.top();
postFix.pb(oper), operators.pop();
}
operators.pop();
}
i++;
}
while(!operators.empty())
{
oper.oper = true;
oper.nr = operators.top();
postFix.pb(oper), operators.pop();
}
}
int evaluateExpr(int a,char op, int b)
{
switch(op)
{
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/': return a/b;
default:
cout<<"probleme";
}
}
void evalRPlr()
{
stack<int> stac;
int operand1,operand2,token;
for(int i = 0 ; i < postFix.size(); i++)
if(postFix[i].oper)
{
operand2 = stac.top(); stac.pop();
operand1 = stac.top(); stac.pop();
token = postFix[i].nr;
result = evaluateExpr(operand1,token,operand2);
stac.push(result);
}
else
stac.push(postFix[i].nr);
result = stac.top(); stac.pop();
}
int main()
{
string s;
in >> s;
shutingYard(s);
evalRPlr();
out<<result;
return 0;
}