Pagini recente » Cod sursa (job #694288) | Cod sursa (job #2297068) | Cod sursa (job #1728993) | Cod sursa (job #104512) | Cod sursa (job #2828914)
#include <iostream>
#include <stack>
#include <cstring>
#include <fstream>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char s[100001];
stack <char> operatori;
stack <int> operanzi;
int formare_nr(char a[], int st, int dr)
{
int nr = 0;
for(int i = st; i <= dr; ++i)
nr = nr * 10 + (a[i] - '0');
return nr;
}
int prioritate(char c)
{
if(c == '+')
return -1;
if(c == '-')
return 0;
if(c == '*' || c == '/')
return 1;
return 2;
}
int pot(char deja, char adaug)
{
if(prioritate(deja) > prioritate(adaug) && prioritate(deja) != 2)
return 0;
return 1;
}
int calcul(int x, int y, char c)
{
if(c == '+')
return x + y;
if(c == '-')
return x - y;
if(c == '*')
return x * y;
return x / y;
}
int evaluare()
{
int l = strlen(s);
for(int i = 0; i < l; ++i)
{
//cout << s[i] << ' ';
if(operatori.empty() && !isalnum(s[i]))
operatori.push(s[i]);
else if(s[i] >= '0' && s[i] <= '9')
{
int st = i, dr;
for(dr = i + 1; isalnum(s[dr]); ++dr);
dr--;
int nr = formare_nr(s, st, dr);
operanzi.push(nr);
i = dr;
}
else if(s[i] == ')')
{
if(operatori.top() == '(')
operatori.pop();
else
{
while(!operatori.empty() && operatori.top() != '(')
{
int x = operanzi.top();
operanzi.pop();
int y = operanzi.top();
operanzi.pop();
char c = operatori.top();
operatori.pop();
int rez = calcul(y, x, c);
operanzi.push(rez);
}
operatori.pop();
}
}
else
{
if(pot(operatori.top(), s[i]))
operatori.push(s[i]);
else
{
while(!operatori.empty() && pot(operatori.top(), s[i]) == 0)
{
int x = operanzi.top();
operanzi.pop();
int y = operanzi.top();
operanzi.pop();
char c = operatori.top();
operatori.pop();
int rez = calcul(y, x, c);
operanzi.push(rez);
}
operatori.push(s[i]);
}
}
}
int rez = operanzi.top();
while(!operatori.empty())
{
int x = operanzi.top();
operanzi.pop();
int y = operanzi.top();
operanzi.pop();
char c = operatori.top();
operatori.pop();
rez = calcul(y, x, c);
operanzi.push(rez);
}
return rez;
}
int main()
{
fin.getline(s, 100001);
fout << evaluare();
return 0;
}