Computation Using A Stack

Pages: 12
I don't see what I'm doing wrong in the set up of the stack. Do you see what could be the problem?
Tomorrow I should have the time for a closer look.
Ok thanks Thomas. I'll try to find a solution in the mean time.
Two small trivial things .....

Why is it that nearly everyone forgets to check for divide by zero?

And this may not be an issue right now, but integer division is not a problem?
Last edited on
The problem was with converting char to int.
This should work now:
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
//EVALUATING POSTFIX EXPRESSION//

  LinkedStack result;


  string postfix = output.str ();

  for (int i = 0; i < postfix.size (); i++)
  {
    if (isdigit (postfix[i]))
    {
      int value = postfix[i] - '0';
      result.pushVal (value);
    }
    else
    {
      int op2 = result.topVal ();
      result.pop ();
      int op1 = result.topVal ();
      result.pop ();
      int value = eval (op1, op2, postfix[i]);
      result.pushVal (value);
    }
  }
  cout << "The final result is " << result.topVal () << "." << endl;


TheIdeasMan is right, check for divide by zero.
It's also worth to check the input that is doesn't contain any illegal chars.
Thank you! I don't see why it made a difference though if you converted from char to int before pushing the operand onto the stack instead of converting it from char to int after popping the operands from the stack, but it does work now.

TheIdeasMan. Ah yes that is very important. Thanks for reminding me about that. As for the division, should I use float instead of int?
As for the division, should I use float instead of int?


Prefer double rather than float. Float only has 6 o 7 digits of precision so that is easily exceeded. double has 15 or 16 digits so that is why it is the default.

Good Luck!!
Ah I see. Thanks!
Topic archived. No new replies allowed.
Pages: 12