Hello, I'm trying to make a Stack that pushes in numbers and Operator's and then does the math.
I.E 4, 3, 5, *, +. = 3*5 = 15 push back on. pop 4 + 15 =19 push back on.
This is all I can think of so far. Not sure How to make the Char operators to work with int's in a stack.
It's not complete because, I'm drawing a blank on where to go from here. The Program shell Main(), Eval(), and Input() is how the teacher wants it to look.
#include <iostream>
#include <stack>
using namespace std;
stack <int> operands;
void main()
{
int Max_List;
cout<< "Input the Total number of Integers you are going to use" << endl;
cin>> Max_List;
evaluate(Max_List);
}
void evaluate(int max)
{
input(max);
int test = max;
int result, temp1, temp2;
while(max > 0)
{
if(!operands.empty() && test > 1)
{
temp1 = operands.top();
operands.pop();
temp2 = operands.top();
}
else if (test == 1)
{
cout<< operands.top() << " Is your result" << endl;
}
test--;
max --;
}
cout<< "Stack is Empty" << endl;
}
void input(int max)
{
int Num;
while(max > 0)
{
cout<< "Input a Number(s) to be calculated " << endl;
cin>> Num;
operands.push(Num);
max --;
}
}
I do not think you need to stack operators. With such "Reversed Polish Notation" they should be executed as soon as you read them.
Try to rewrite your program as following:
1) initialize empty stack for numbers;
2) read next token (sequence of non-space characters);
3) if token is not one of operator's characters, then convert it to number and push into stack;
4) otherwise pop two numbers from stack and apply operator to them (use "switch" statement with 4 branches);
5) if it was not the end of input, go to 2;
6) otherwise print result.
Perhaps it is better not to ask about "how much numbers would be entered, but instead use some special "operator" like exclamation mark to signalize end of input.
One more thing...How do I use...or Make the case's take operators.
1 2
char op; // Which takes in the Operators.
op = operators.front();
as a switch
1 2 3 4 5 6 7 8 9 10 11
switch (op)
case /: result = temp1 / temp2;
break;
case *: result = temp1 * temp2;
break;
case -: result = temp1 - temp2;
break;
case +: result = temp1 + temp2;
break;
default: cout<< " no" << endl;