Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stack>
- using namespace std;
- int evaluate(const char* expr);
- int main()
- {
- //cout << evaluate("+(*(2,3), 4, +(4,5,6))") << endl;
- char expr[100];
- cout << "Enter expression: ";
- cin.getline(expr, 100);
- cout << "Result = " << evaluate(expr) << endl;
- return 0;
- }
- int evaluate(const char* expr)
- {
- stack<int> stArguments;
- stack<char> stOperations;
- while(*expr)
- {
- if (*expr == '+' || *expr == '*')
- {
- stOperations.push(*expr);
- }
- else if (*expr >= '0' && *expr <= '9')
- {
- stArguments.push(*expr - '0');
- }
- else if (*expr == '(')
- {
- stArguments.push('(');
- }
- else if (*expr == ')')
- {
- int result = 0;
- if (stOperations.top() == '*')
- {
- result = 1;
- while (!stArguments.empty() && stArguments.top() != '(')
- {
- result *= stArguments.top();
- stArguments.pop();
- }
- }
- if (stOperations.top() == '+')
- {
- while (!stArguments.empty() && stArguments.top() != '(')
- {
- result += stArguments.top();
- stArguments.pop();
- }
- }
- stOperations.pop();
- stArguments.pop(); // remove '('
- stArguments.push(result);
- }
- expr++;
- }
- return stArguments.top();
- }
Add Comment
Please, Sign In to add comment