Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<deque>
- #include<cstdlib>
- #include<cstring>
- using namespace std;
- int compute(deque<int> &numbers, deque<char> &operators) {
- char operation;
- int operand1, operand2, t;
- while(!operators.empty()) {
- operation = operators.front(); operators.pop_front();
- operand1 = numbers.front(); numbers.pop_front();
- operand2 = numbers.front(); numbers.pop_front();
- if(operation == '+') t = operand1 + operand2;
- else if(operation == '-') t = operand1 - operand2;
- else if(operation == '/') t = operand1 / operand2;
- else if(operation == '*') t = operand1 * operand2;
- numbers.push_front(t);
- }
- int result = numbers.front(); numbers.pop_front();
- return result;
- }
- void evaluate(char* exp) {
- deque<int> numbers, numbers_brackets;
- deque<char> operators, operators_brackets;
- char* token = strtok(exp, " ");
- while(token != NULL) {
- if(isdigit(token[0])) numbers.push_back(atoi(token));
- else if(token[0] == '+' || token[0] == '-' || token[0] == '/' || token[0] == '*') {
- operators.push_back(token[0]);
- } else if(token[0] == '(') {
- token = strtok(NULL, " ");
- while(token != NULL && token[0] != ')') { //assuming input is valid w.r.t to brackets
- if(isdigit(token[0])) numbers_brackets.push_back(atoi(token));
- else if(token[0] == '+' || token[0] == '-' || token[0] == '/' || token[0] == '*') operators_brackets.push_back(token[0]);
- token = strtok(NULL, " ");
- }
- numbers.push_back(compute(numbers_brackets, operators_brackets)); // Compute things within bracket and push_back the result to the original stack
- }
- token = strtok(NULL, " ");
- }
- cout << "Ans:" << compute(numbers,operators) << endl;
- }
- int main() {
- char input[100];
- scanf("%[^\n]s",input);
- evaluate(input);
- }
Advertisement
Add Comment
Please, Sign In to add comment