Pagini recente » Cod sursa (job #2039062) | Cod sursa (job #2024090) | Cod sursa (job #2270014) | Cod sursa (job #2852856) | Cod sursa (job #2265839)
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <stack>
#include <cstdlib>
#include <sstream>
using namespace std;
int getPriority(string s) {
if (s == "(") {
return 0;
}
if (s == "+" || s == "-") {
return 1;
}
return 2;
}
int main() {
ifstream in("evaluare.in");
ofstream out("evaluare.out");
vector<string> reverseNotation;
string input;
stack<string> operandStack;
in >> input;
for (int i = 0; i < input.size(); i++) {
if (isdigit(input[i])) {
string temp = "";
while (isdigit(input[i])) {
temp += (char)(input[i]);
i++;
}
reverseNotation.push_back(temp);
i--;
} else if (input[i] == '(') {
operandStack.push("(");
} else if (input[i] == ')') {
while (operandStack.top() != "(") {
reverseNotation.push_back(operandStack.top());
operandStack.pop();
}
operandStack.pop();
} else {
string temp = "";
temp += (char)(input[i]);
while (!operandStack.empty() && getPriority(operandStack.top()) >= getPriority(temp)) {
reverseNotation.push_back(operandStack.top());
operandStack.pop();
}
operandStack.push(temp);
}
}
while (!operandStack.empty()) {
reverseNotation.push_back(operandStack.top());
operandStack.pop();
}
int result = 0;
stack<string> result_operand_stack;
for (auto token : reverseNotation) {
if (token == "+" || token == "*" || token == "-" || token == "/") {
string first = result_operand_stack.top();
result_operand_stack.pop();
string second = result_operand_stack.top();
result_operand_stack.pop();
if (token == "+") {
result = atoi(first.c_str()) + atoi(second.c_str());
} else if (token == "*") {
result = atoi(first.c_str()) * atoi(second.c_str());
} else if (token == "-") {
result = atoi(second.c_str()) - atoi(first.c_str());
} else if (token == "/") {
result = atoi(second.c_str()) / atoi(first.c_str());
}
ostringstream tmp;
tmp << result;
result_operand_stack.push(tmp.str());
} else {
result_operand_stack.push(token);
}
}
out << result;
in.close();
out.close();
return 0;
}