Adding 2 numbers using stack?

Apr 13, 2011 at 2:59pm
I'm trying to solve this math problem using stacks:
10-4*2+8/10


I know I have to create two different stacks (numbers and operands).

I want to start very simple before I figure out how to do the whole problem.
So, I would like to use this problem:
10+5


I pushed 10 and 5 in the numbers stack and I also pushed + in the operands stack.
But I don't know exactly what to do from there.

I can figure out the top number, which is 5, but how do I get down to the 10?
Also, how do I get it to add each other?

I'm just new to stacks, so if anyone could explain, please do it so I can understand. Thanks.

Here's my attempt which obviously does not work like it's supposed to:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <stack>
using namespace std;

int main()
{
	stack<int> number;
	stack<char> operand;

	number.push(10);
	number.push(5);
	operand.push('+');

	cout << number.top() << operand.top() << number.top() << endl;

	system("pause");
}
Apr 13, 2011 at 4:02pm
Write a function add() that pops the first number from the stack and saves it somewhere, than pops the second one and adds it to the first one. Then pushes the result.
Apr 13, 2011 at 4:07pm
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
#include <iostream>
#include <stack>
using namespace std;

int add(int a, int b);

int main()
{
	int e, r, z;
	stack<int> number;
	stack<char> operand;

	number.push(10);
	number.push(5);
	operand.push('+');

	if (operand.top() == '+')
	{
	e = number.top();
	number.pop();
	r = number.top();
	cout << e << "+" << r << endl;
	z = add(e, r);
	cout << z << endl;
	}

	system("pause");
}

int add(int a, int b)
{
	int x;
	x = a + b;
	return (x);
}


Thanks!
Topic archived. No new replies allowed.