The program is supposed to evaluate a line of mathematical expression, then push and pop operands and operators respectively into two different stacks.
Problem is, that although the code looks fine to me as I wrote it, and even though it compiles just fine, as soon as I enter in an equation and hit enter, I get a nice fancy "Expression: deque iterator not dereferencable" error.
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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
|
int evaluate(string expression)
{
istringstream in;
in.str(expression);
stack <int> Operands;
stack <char> Operators;
char operators;
int operands;
int num1;
int num2;
int result;
/*int eqtop = 0;*/
/*int top;*/
int tempNum;
char tempChar;
//char peek = in.peek();
while ( in.good() )
{
//read operand
in >> operands;
if(in.good())
{
Operands.push(operands);
}
//read in operator
in >> operators;
if (Operators.empty())
{
if (in.good())
Operators.push(operators);
}
else if (!Operators.empty())
{
//in >> operators;
if (Operators.top() != '*' && Operators.top() != '/')
{
if (in.good())
Operators.push(operators);
}
if (Operators.top() == '*' || Operators.top() == '/')
{
tempChar = Operators.top();
Operators.pop();
num1 = Operands.top();
Operands.pop();
num2 = Operands.top();
if (tempChar == '*')
{
result = num1 * num2;
Operands.pop();
Operands.push(result);
}
if (tempChar == '/')
{
result = num1/num2;
Operands.pop();
Operands.push(result);
}
Operators.push(operators);
}
/*tempChar = operators;*/
}
}
while (!Operators.empty())
{
tempChar = Operators.top();
if (tempChar == '+')
{
num1 = Operands.top();
Operands.pop();
num2 = Operands.top();
result = num1 + num2;
Operands.pop();
Operands.push(result);
}
else if (tempChar == '-')
{
num1 = Operands.top();
Operands.pop();
num2 = Operands.top();
result = num1 - num2;
Operands.pop();
Operands.push(result);
}
Operators.pop();
}
result = Operands.top();
return result;
}
|
I have a hunch it has to do with the program trying to access a stack that is already empty somewhere. Nothing seems to be accessing any stack before it attempts to access its top or tries to pop anything empty though, at least nothing I see.
I've also read somewhere on the General C++ Programming forum about someone with a similar problem, and mentioned something about using pointers? Problem is, although I'm experienced with vectors, classes, and so on, I'm not a genius with pointers.
What do you guys think? Am I overlooking something?