Help with Stacks!

I have to create a function which takes a string of a postfix equation, convert it into an int and push it in a stack. Then, if the string contains any operations such as +,-,*,/(which it obviously does), it will pop the elements from the stack, perform the operation, then push the result back into the stack.

Example:
string = "5 7 * 9 3 / +"

Logically, my program needs to push elements 5 and 7 onto a stack, then it comes to its first operation, *, which it will pop back 7 and 5, assign them to two int variables, multiply the two variables, then push the result back into the stack.

Stack contained(5, 7), then i = *, Stack contains(35).

My program keeps reaching a breaking point when it reaches the second if statement which checks if the string contains an operation.

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
int main()
{
	string Expression;
	Expression = "5 7 * 9 3 / +"; //this evaluated to (5*7) + (9/3)
	cout << "Default postfix expression: " << Expression << endl;
	//result in 38
	solvePostfix(Expression);


	system("PAUSE");
	return 0;
}

void solvePostfix(string postfixExp)
{
	Stack *exp = new Stack(); //double stack 
	int char2int;
	for (int i = 0; i < postfixExp.size(); i++)
	{
		if (postfixExp[i] >= char(48) && postfixExp[i] <= char(57)) //if string index is 0 to 9
		{
			//need to convert char to int before push
			istringstream buffer(postfixExp[i]);
			buffer >> char2int;
			exp->push(char2int); 
		}
	
		if (postfixExp[i] == '+'|| postfixExp[i] == '-' || postfixExp[i] == '*' || postfixExp[i] == '/' || postfixExp[i] == '%')
		{
			int x, y = 0;
			x = exp->top();
			exp->pop();
			y = exp->top();
			exp->pop();
			switch (postfixExp[i])
			{
			case '+': exp->push(y + x); break;
			case '-': exp->push(y - x); break;
			case '*': exp->push(x*y); break;
			case '/': exp->push(y / x); break;
			case '%': exp->push(y%x); break;
			}
		}
	}
	cout << "The result of postfix evaluation of: " << postfixExp << "is: " << exp->top() << endl;
	exp->pop();

}


Topic archived. No new replies allowed.