Stack not working as intended

I have an assignment where I have to create a calculator which accepts a string containing a POSTFIX equation.

My program compiles and executes, but it keeps saying that there is nothing to pop because the stack is empty, which means that there is a problem when I am calling the push function, as perhaps the elements are not getting pushed in.

My stack implementation is basic, aside for these functions:
1
2
3
4
5
6
7
8
9
10
void Stack::growStack(int newCapacity)
{
	double *x = new double[newCapacity];
	for (int i = 0; i < capacity; i++)
	{
		x[i] = s[i];
	}
	delete[] s;
	s = x;
}


This only gets called in my push function if isFull() returns true

Here is my main code:
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
72
73
74
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; //double stack 
	exp.ClearStack(); //make sure stack is cleared, no data
	double num;

	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 (istringstream(postfixExp[i]) >> num)
		{
			exp.push(num);
		}

		else if (postfixExp[i] == '+' || postfixExp[i] == '-' || postfixExp[i] == '*' || postfixExp[i] == '/')
		{
			Equation(postfixExp, exp);
		}
		
	}
	cout << exp.top() << endl;
	exp.pop();

}

void Equation(const string &postfix, Stack &x)
{
	double left, right;
	right = x.top();
	x.pop();
	left = x.top();
	x.pop();
	if (postfix == "+")
	{
		x.push(Add(left, right));
	}
	else if (postfix == "-")
	{
		x.push(Sub(left, right));
	}
	else if (postfix == "*")
	{
		x.push(Multi(left, right));
	}
	else if (postfix == "/")
	{
		x.push(Div(left, right));
	}
	else if (postfix == "%")
	{
		x.push(Mod(left, right));

	}

}
Last edited on
Have you stepped through with a debugger? This would tell you exactly where the issue is happening. I highly recommend you spend an hour familiarizing yourself with your debugger, as that is an incredibly valuable skill.

I can't be of much help without seeing your Stack code.
Topic archived. No new replies allowed.