Pagini recente » Cod sursa (job #1366917) | Cod sursa (job #3236381) | Cod sursa (job #382365) | Cod sursa (job #554361) | Cod sursa (job #1678217)
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
using namespace std;
stack<int> nr;
stack<char> sg;
void e(char c)
{
int x, y;
x = nr.top();
nr.pop();
y = nr.top();
nr.pop();
int r;
switch(c)
{
case '+':{r = y+x; break;}
case '-':{r = y-x; break;}
case '*':{r = y*x; break;}
case '/':{r = y/x; break;}
}
nr.push(r);
}
void par()
{
char c = sg.top();
while(c != '(')
{
e(c);
sg.pop();
c = sg.top();
}
sg.pop();
}
int pr(char c)
{
switch(c)
{
case '+':
case '-':{return 1; break;}
case '*':
case '/':{return 2; break;}
default:{return 0; break;}
}
}
void eop(char c)
{
int prc = pr(c);
if(!sg.empty())
{
char tc = sg.top();
while(pr(tc) >= prc && !sg.empty())
{
e(tc);
sg.pop();
tc = sg.top();
}
}
sg.push(c);
}
void op(char c)
{
switch (c)
{
case '(':{sg.push(c); break;}
case ')':{par(); break;}
default:{eop(c); break;}
}
}
int main()
{
ifstream f("evaluare.in");
ofstream g("evaluare.out");
char c;
bool pc = 0;
int w = 1;
f >> c;
while(!f.eof())
{
int x = 0;
while(isdigit(c) && !f.eof())
{
pc = 1;
x *= 10;
x += c-'0';
f >> c;
}
if(pc)
nr.push(x*w), w = 1;
if(!isdigit(c))
{
if(w == -1)
{
sg.push('-');
w = 1;
}
if(c == '-' && !pc)
w = -1;
else
op(c);
pc = 0;
}
f >> c;
}
while(!sg.empty())
{
e(sg.top());
sg.pop();
}
g << nr.top();
}