Pagini recente » Cod sursa (job #2792394) | Cod sursa (job #1907134) | Cod sursa (job #1782273) | Cod sursa (job #3148288) | Cod sursa (job #3293934)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string expresie;
stack <char> operatori;
stack <int> numere;
vector<char>ordine;
int numar, aux;
map<char, int> imp =
{
{'*', 2},
{'/', 2},
{'+', 1},
{'-', 1}
};
int realizare_operatie(stack<int>& numere, stack<char>& operatori )
{
int valoare2, valoare1;
valoare2 = numere.top();
numere.pop();
valoare1 = numere.top();
numere.pop();
char opr;
opr = operatori.top();
operatori.pop();
int rezultat;
if ( opr == '+')
{
rezultat = valoare1 + valoare2;
}
if( opr == '-')
{
rezultat = valoare1 - valoare2;
}
if( opr == '*')
{
rezultat = valoare1 * valoare2;
}
if(opr == '/')
{
rezultat = valoare1 / valoare2;
}
return rezultat;
}
int main()
{
fin >> expresie;
for(int i = 0; i < expresie.size(); i++)
{
if( expresie[i] <= '9' && expresie[i] >= '0')
{
numar = 0;
while(expresie[i] <= '9' && expresie[i] >= '0')
{
numar = numar * 10 + (expresie[i] - '0');
i++;
}
i--;
numere.push(numar);
}
else if (expresie[i] == '(' )
{
operatori.push('(');
}
else
{
if( expresie[i] == ')')
{
while( operatori.top() != '(')
aux = realizare_operatie(numere, operatori);
numere.push(aux);
operatori.pop();
}
else
{
while(operatori.size() != 0 && imp[operatori.top()] >= imp[expresie[i]] )
{
aux = realizare_operatie(numere, operatori);
numere.push(aux);
}
operatori.push(expresie[i]);
}
}
}
while(operatori.size() != 0)
{
aux = realizare_operatie(numere, operatori);
numere.push(aux);
}
fout << numere.top();
numere.pop();
return 0;
}