Pagini recente » Cod sursa (job #2215908) | Cod sursa (job #1897118) | Cod sursa (job #3291474) | Cod sursa (job #532602) | Cod sursa (job #948459)
Cod sursa(job #948459)
#include <iostream>
#include<vector>
#include<stack>
#include<stdio.h>
#include <string>
#include<fstream>
using namespace std;
vector<int> nr;
stack<int> operanzi;
stack<char>operatori;
bool esteparanteza(const char& c)
{
if(c=='('||c==')')
return true;
return false;
}
bool estenumar(const char&c)
{
if(c>='0'&&c<='9')
return true;
return false;
}
bool prioritate(const char&nou,const char&vechi)
{
if((nou=='+'||nou=='-')&&(vechi=='*'||vechi=='/'))
return true;
return false;
}
string procesare(string expresie)
{
int i=0;
char c;
string ret;
operatori.push('x');
while(i<expresie.size())
{
c=expresie[i];
if(esteparanteza(c))
{
if(c=='(')
{
operatori.push(c);
i++;
}
else{
c=operatori.top();
while(c!='(')
{
ret+=c;
operatori.pop();
c=operatori.top();
}
operatori.pop();
i++;
}
}
else
{
if(estenumar(c))
{
ret+='0';
int n=0;
while(i<expresie.size()&&estenumar(expresie[i]))
{
n*=10;
n+=expresie[i]-'0';
i++;
}
nr.push_back(n);
}
else
{
char d;
d=operatori.top();
while(prioritate(c,d))
{
ret+=d;
operatori.pop();
d=operatori.top();
}
operatori.push(c);
i++;
}
}
}
while(operatori.top()!='x')
{
c=operatori.top();
if(c!=')')
ret+=c;
operatori.pop();
}
return ret;
}
int evaluare(string& fp)
{
char c;
int i=0,j=0;
while(i<fp.size())
{
c=fp[i];
if(c=='0')
{
operanzi.push(nr[j]);
j++;
i++;
}
else
{
int a, b,rez;
b=operanzi.top();
operanzi.pop();
a=operanzi.top();
operanzi.pop();
switch(c)
{
case '+':rez=a+b; break;
case '-':rez=a-b; break;
case '*':rez=a*b;break;
case '/':rez=a/b;break;
}
operanzi.push(rez);
i++;
}
}
return operanzi.top();
}
int main()
{
string expresie,fp;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
getline(fin,expresie);
fp=procesare(expresie);
fout<<evaluare(fp)<<'\n';
return 0;
}