evaluating postfix expression using stacks
Nov 3, 2013 at 7:46pm UTC
i feel like im really close to completing this but i cant seem to get the result printed out
i dont think im calling my evaluate function correctly and its not performing the operations..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
#include <iostream>
#include <stack> //stack header file
using namespace std;
typedef stack<int > stack_type;
char input(char &);
void evaluate(stack_type&, char &);
int main()
{
char op;
stack_type operands;
cout << "Enter how many numbers you want in your expression" << endl;
input(op);
evaluate(operands, op);
}
char input(char & op)
{
int x;
stack_type operands;
int numberAmount;
int count = 0;
cin >> numberAmount;
cout << "Enter " << numberAmount << " numbers" << endl;
while (numberAmount > 0) {
cin >> x;
operands.push(x);
numberAmount--;
count++;
}
count = count -1;
cout << "Enter " << count <<" operators" << endl;
while (count > 0) {
cin >> op;
count--;
}
evaluate(operands, op);
return op;
}
void evaluate(stack_type& operands, char & op)
{
input(op);
while (operands.size() > 1)
{
int a = operands.top();
operands.pop();
int b = operands.top();
operands.pop();
int result;
switch (op)
{
case '+' : result = a + b; break ;
case '*' : result = a * b; break ;
case '/' : result = a / b; break ;
case '%' : result = a % b; break ;
case '-' : result = a - b; break ;
default :
cout << "You have entered an incorrect operator" ;
}
cout << result << endl;
operands.push(result);
}
cout << operands.top() << endl;
}
Nov 4, 2013 at 2:43am UTC
anyone?
Topic archived. No new replies allowed.