Pagini recente » Cod sursa (job #2826409) | Cod sursa (job #646070) | Cod sursa (job #1230931) | Cod sursa (job #296499) | Cod sursa (job #3253352)
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
using namespace std;
ifstream input("evaluare.in");
ofstream output("evaluare.out");
int getNextNum(string &expression, int &pos)
{
int result = 0;
while(expression[pos] >= '0' && expression[pos] <= '9' && pos < expression.size()){
result = 10*result + expression[pos] - '0';
pos++;
}
pos--;
return result;
}
void evaluateOperation(stack<int> &st_num, char operation)
{
int num1 = st_num.top();
st_num.pop();
int num2 = st_num.top();
st_num.pop();
if(operation == '+'){
st_num.push(num2 + num1);
}
else if(operation == '-'){
st_num.push(num2 - num1);
}
else if(operation == '*'){
st_num.push(num2 * num1);
}
else{
st_num.push(num2 / num1);
}
}
int precedence(char operation)
{
if(operation == '+' || operation == '-'){
return 1;
}
if(operation == '*' || operation == '/'){
return 2;
}
}
int main()
{
string expression;
input >> expression;
stack<int> st_num;
stack<char> st_op;
int pos = 0;
while(pos < expression.size()){
char next_char = expression[pos];
int next_num = 0;
if(next_char >= '0' && next_char <= '9'){
next_num = getNextNum(expression, pos);
st_num.push(next_num);
}
else if(next_char == '('){
st_op.push(next_char);
}
else if(next_char == ')'){
while(st_op.top() != '('){
char operation = st_op.top();
st_op.pop();
evaluateOperation(st_num, operation);
}
st_op.pop();
}
else{
char op1 = next_char;
if(!st_op.empty()){
char op2 = st_op.top();
while(!st_op.empty() && op2 != '(' && precedence(op2) >= precedence(op1)){
op2 = st_op.top();
st_op.pop();
evaluateOperation(st_num, op2);
}
}
st_op.push(op1);
}
pos++;
}
while(!st_op.empty()){
char operation = st_op.top();
st_op.pop();
evaluateOperation(st_num, operation);
}
output << st_num.top();
return 0;
}