Pagini recente » Cod sursa (job #1449080) | Cod sursa (job #363642) | Cod sursa (job #2660097) | Cod sursa (job #2785120) | Cod sursa (job #1090524)
#include <fstream>
#include <iostream>
#include <string.h>
using namespace std;
struct operanzi{
char q;
short precedence;
}s[100010];
struct operators{
char c;
short prec;
}op[4];
int isOperator(char c)
{
op[0]={'+', 1};
op[1]={'-',1};
op[2]={'*',2};
op[3]={'/',2};
for(int i=0;i<4;i++)
{
if(c==op[i].c) return op[i].prec;
}
return 0;
}
bool isDigit(char c)
{
if(c>='0' && (c<='9')) return 1;
return 0;
}
int eval(int a, int b, char c)
{
switch(c)
{
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/': return a/b;
}
}
int main()
{
int nrs[100010];
ifstream f("evaluare.in");
ofstream g("evaluare.out");
int i,p,l,n=-1,k=-1,nr;
char e[200];
f.getline(e,200);
l=strlen(e);
for(i=0;i<l;i++)
{
//If you find a number, output it
if(isDigit(e[i]))
{
nr=0;
while(isDigit(e[i]))
{
nr=nr*10+(e[i]-'0');
i++;
}
i--;
nrs[++k]=nr;
}
//If you reach an operator
else if(p=isOperator(e[i]))
{
//If the stack is empty, push it
if(n==-1)
{
s[++n].q=e[i];
s[n].precedence=p;
}
//If the Stack isn't empty and S[n] is higher or equal then pop s[n] and push e[i]
else
if(s[n].precedence>=p)
{
while((s[n].precedence>=p)&&(n>=0))
{
nrs[k-1]=eval(nrs[k-1],nrs[k],s[n].q);
k--;
n--;
}
s[++n].q=e[i];
s[n].precedence=p;
}
//Else s[n] is lower and push S[n] into stack
else {
s[++n].q=e[i];
s[n].precedence=p;
}
}
//If you reach a '('
else if(e[i]=='(')
{
s[++n].q=e[i];
s[n].precedence=0;
}
//If you reach a ')'
else if(e[i]==')')
{
while(s[n].q!='(')
{
nrs[k-1]=eval(nrs[k-1],nrs[k],s[n].q);
n--;
k--;
}
n--;
}
}
while(n>=0)
{
nrs[k-1]=eval(nrs[k-1],nrs[k],s[n].q);
n--;
k--;
}
g<<nrs[k];
}