Pagini recente » Cod sursa (job #3238283) | Cod sursa (job #1983509) | Cod sursa (job #479015) | Cod sursa (job #1910647) | Cod sursa (job #3291534)
#include <fstream>
#include <string>
#include <stack>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
int opr(char c) {
if (c == '+' || c == '-')
return 1;
if (c == '*' || c == '/')
return 2;
if (c == '(')
return -1;
throw "Ce-ai facut prietene? Ai aruncat un operator necunoscut";
}
void calc(stack<int>& numere, stack<char>& operatori) {
int b = numere.top();
numere.pop();
int a = numere.top();
numere.pop();
char op = operatori.top();
operatori.pop();
switch (op) {
case '+':
numere.push(a + b);
break;
case '-':
numere.push(a - b);
break;
case '*':
numere.push(a * b);
break;
case '/':
if (b == 0)
throw "Nu se poate prietene sa imparti la 0 ;)";
numere.push(a / b);
break;
default:
throw "Ai aruncat un operator necunoscut";
}
}
int main() {
string s;
fin >> s;
stack<int> numere;
stack<char> operatori;
for (int i = 0; i < s.size(); i++) {
if (isdigit(s[i]))
{
int n = 0;
while (i < s.size() && isdigit(s[i])) {
n = n * 10 + (s[i] - '0');
++i;
}
--i; // skip double increment
numere.push(n);
}
else if (s[i] == '(')
{
operatori.push('(');
}
else if (s[i] == ')')
{
while (operatori.top() != '(')
calc(numere, operatori);
operatori.pop(); // pop (
}
else
{
// calculate the expression
while (!operatori.empty() && opr(operatori.top()) >= opr(s[i]))
calc(numere, operatori);
operatori.push(s[i]);
}
}
while (!operatori.empty())
calc(numere, operatori);
fout << numere.top() << '\n';
return 0;
}