Pagini recente » Cod sursa (job #1079384) | Cod sursa (job #63431) | Cod sursa (job #857995) | Cod sursa (job #692290) | Cod sursa (job #3286252)
#include <iostream>
#include <fstream>
#include <stack>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string s;
stack<int>numere;
stack<char>oper;
bool is_op(char c)
{
if (c == '+' || c == '-' || c == '*' || c == '/')
return 1;
return 0;
}
int priority_operator(char c)
{
if (c == '+' || c == '-')
return 1;
if (c == '*' || c == '/')
return 2;
return -1;
}
void process_op()
{
int a = numere.top();
numere.pop();
int b = numere.top();
numere.pop();
char c = oper.top();
if (c == '+')
numere.push(a + b);
else
{
if (c == '-')
numere.push(b - a);
else
{
if (c == '*')
numere.push(a * b);
else if(c=='/')
numere.push(b / a);
}
}
}
int main()
{
fin >> s;
for (int i = 0; i < s.size(); i++)
{
if (s[i] == '(')
oper.push('(');
else
{
if (s[i] == ')')
{
while (oper.top() != '(')
{
process_op();
oper.pop();
}
oper.pop();
}
else
{
if (is_op(s[i]))
{
char c = s[i];
while (!oper.empty() && (priority_operator(oper.top()) >= priority_operator(c)))
{
process_op();
oper.pop();
}
oper.push(c);
}
else
{
int nr = 0;
while (i < s.size() && isdigit(s[i]))
{
nr = nr * 10 + s[i] - '0';
i++;
}
i--;
numere.push(nr);
}
}
}
}
while (!oper.empty())
{
process_op();
oper.pop();
}
fout << numere.top();
return 0;
}