@dhayden
I did not catch that bug in empty(), thank you!
Awesome, thank you that took care of the error I was getting! Now that my code is running though, I am getting wrong answers for some equations ): Particularly I noticed in some examples, the last operation pops all my data in my stacks, and when I return the popped function in the end, I just receive the last number in the equation. The examples I am getting the wrong answers for are '17 / ( 2 + 3 ) - 13' and '2 ^ 3 ^ 2' in both cases I am returning the last value , 13 and 2 respectively. With the cout statements you provided to help trace my code, it shows that the operator is being recognized and pushed into the stack, but by the next loop it is popped out and I am left with empty stacks for both my operands and operators. I am not sure where I am losing the value in my operands stack.
Edit: I figured out part of the problem, whenever I would call
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
else if (isOperator(infix[i]) == true)
{
if (operators.empty() == true || precedence(infix[i]) > precedence(operators.top()))
{
std::cout << "Top is called\n";
operators.push(infix[i]);
}
else
{
int valueOne = operands.pop();
int valueTwo = operands.pop();
char op = operators.pop();
operands.push(operate(valueOne, valueTwo, op));
}
}
|
In my else statement, I would lose the operator currently in infix, I fixed this by just pushing that operator onto the stack after I did the operation in my else statement. This fixed the problem I was having in the equation '17 / ( 2 + 3) - 13' however, I am still getting the wrong answer for '2^3^2, I am not getting the last number as my answer anymore, but I am still getting the wrong answer. I thought it had to do with my precedence since they are the same operation, so I changed the condition in my if statement to being greater than or equal to, but this did not help. Any idea why I am not getting the right answer?
Edit #2: Changing it to greater than or equal to did help. My problem lies in my while loop at the end
1 2 3 4 5 6 7
|
while (operators.empty() != true)
{
int valueOne = operands.pop();
int valueTwo = operands.pop();
char op = operators.pop();
operands.push(operate(valueOne, valueTwo, op));
}
|
In the last iteration, I always end up with an empty operands stack, which I am not sure why I am if the last line of code should be pushing the value after it operates. Do you know why I am ending with an empty stack after this? For now, I just have an inefficient solution. I just made an integer value so I could store the final answer. I set the final answer to the top of the stack after the for loop, and I set it equal to operate after the operands.push(operate()) function in the while loop. I get the correct answers by doing this, but I am sure there is a more efficient way to fix my while loop instead.