Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /** @author
- * @file main.cpp */
- #include <iostream>
- #include <stack>
- #include <string>
- using namespace::std;
- string infixToPostfix(string parExpression);
- double evaluate(string parExpression);
- int precedence(char parC);
- int main()
- {
- // Test the following cases
- cout << evaluate(infixToPostfix("2-9")) << endl;
- cout << evaluate(infixToPostfix("(3+2)*5")) << endl;
- cout << evaluate(infixToPostfix("(1+7)*(5/2)")) << endl;
- cout << evaluate(infixToPostfix("4+3*5/6")) << endl;
- return 0;
- }
- string infixToPostfix(string parExpression)
- {
- stack<char> theStack;
- string postFixExpression = "";
- for (unsigned int c = 0; c < parExpression.length(); c++)
- {
- switch (parExpression[c])
- {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- postFixExpression = postFixExpression + parExpression[c];
- break;
- case '(':
- theStack.push(c);
- break;
- case '+':
- case '-':
- case '*':
- case '/':
- while ((!theStack.empty()) && (theStack.top() != '(') && (precedence(c) <= precedence(theStack.top())))
- {
- postFixExpression = postFixExpression + theStack.top();
- theStack.pop();
- }
- theStack.push(c);
- break;
- case ')':
- while (theStack.top() != '(')
- {
- postFixExpression = postFixExpression + theStack.top();
- theStack.pop();
- }
- theStack.pop();
- break;
- }
- }
- while (!theStack.empty())
- {
- postFixExpression = postFixExpression + theStack.top();
- theStack.pop();
- }
- return postFixExpression;
- }
- double evaluate(string parExpression)
- {
- stack<double> theStack;
- double result = 0;
- double operand1, operand2;
- for (unsigned int x = 0; x < parExpression.length(); x++)
- {
- if (isdigit(x))
- {
- theStack.push(x);
- }
- else
- {
- operand2 = (double)theStack.top();
- theStack.pop();
- operand1 = (double)theStack.top();
- theStack.pop();
- switch (parExpression[x])
- {
- case '+':
- result = operand1 + operand2;
- theStack.push(result);
- break;
- case '-':
- result = operand1 - operand2;
- theStack.push(result);
- break;
- case '*':
- result = operand1 * operand2;
- theStack.push(result);
- break;
- case '/':
- result = operand1 / operand2;
- theStack.push(result);
- break;
- }
- }
- }
- return theStack.top();
- }
- int precedence(char parC)
- {
- if ((parC == '*') || (parC == '/'))
- return 1;
- else
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement