Pagini recente » Cod sursa (job #3244109) | Cod sursa (job #488785) | Cod sursa (job #380813) | Cod sursa (job #1836211) | Cod sursa (job #1593354)
#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
#include <fstream>
#include <string.h>
#define SIZE 100005
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
void read(char foo[SIZE])
{
f.getline(foo, SIZE);
}
int put_first_two(int &i, char foo[SIZE], stack <int> &num, stack <char> &op)
{
int nbr;
if (strlen(foo) == 0)
return (0);
nbr = 0;
while (foo[i] == '(')
op.push(foo[i++]);
while (foo[i] >= 48 && foo[i] <= 57)
nbr = nbr * 10 + (foo[i++] - 48);
num.push(nbr);
if (i < strlen(foo) - 1)
{
if (foo[i] != '(')
op.push(foo[i++]);
nbr = 0;
while (foo[i] >= 48 && foo[i] <= 57)
nbr = nbr * 10 + (foo[i++] - 48);
num.push(nbr);
return (1);
}
return (0);
}
void deal_with_popping(stack <int> &num, stack <char> &op)
{
int term1, term2;
int result;
while (!op.empty())
{
term2 = num.top();
num.pop();
term1 = num.top();
num.pop();
cout << term1 << ' ' << op.top() << ' ' << term2 << '\n';
if (op.top() == '+')
result = term1 + term2;
else if (op.top() == '-')
result = term1 - term2;
else if (op.top() == '/')
result = term1 / term2;
else if (op.top() == '*')
result = term1 * term2;
num.push(result);
op.pop();
}
}
void deal_with_brackets(stack <int> &num, stack <char> &op)
{
int term1, term2;
int result;
while (op.top() != '(')
{
cout << op.top() << '\n';
term2 = num.top();
num.pop();
term1 = num.top();
num.pop();
cout << term1 << ' ' << op.top() << ' ' << term2 << '\n';
if (op.top() == '+')
result = term1 + term2;
else if (op.top() == '-')
result = term1 - term2;
else if (op.top() == '/')
result = term1 / term2;
else if (op.top() == '*')
result = term1 * term2;
num.push(result);
op.pop();
}
op.pop();
}
void eval_expr(char foo[SIZE])
{
int i;
int nbr;
stack <int> num;
stack <char> op;
i = 0;
if (put_first_two(i, foo, num, op) == 0)
{
num.size() == 1 ? g << num.top() : g << 0;
exit(EXIT_SUCCESS);
}
while (i < strlen(foo))
{
if (foo[i] >= 48 && foo[i] <= 57)
{
nbr = 0;
while (foo[i] >= 48 && foo[i] <= 57)
nbr = nbr * 10 + (foo[i++] - 48);
num.push(nbr);
}
if (foo[i] == '+' || foo[i] == '-')
{
deal_with_popping(num, op);
op.push(foo[i]);
}
if (foo[i] == '*' || foo[i] == '/')
{
if (op.top() == '*' || op.top() == '/')
deal_with_popping(num, op);
op.push(foo[i]);
}
if (foo[i] == '(')
op.push(foo[i]);
if (foo[i] == ')')
{
cout << num.size();
deal_with_brackets(num, op);
}
i++;
}
deal_with_popping(num, op);
g << num.top();
}
int main()
{
char foo[SIZE];
read(foo);
eval_expr(foo);
return 0;
}