Using the stack class with an RPN calculator

Feb 24, 2012 at 4:23am
I have been having troubles with this program for quite a while now. After about a week I finally got the RPN calculator to work as expected, my only trouble is the display prompt. I need the INPUT prompt to display "Enter: " followed by each member of the stack.


Each line of input simply takes one token at a time. ANY help would be much appreciated. Also, this is homework so I don't expect/need anyone to type out code, just throw me in the right direction. Thanks!

Example: (1+2)/(3+4)
Enter: 1 [ENTER]
Enter: 1 2 [ENTER]
Enter: 2 1 + [ENTER]
Enter: 3.000000 3 [ENTER]
Enter: 3 3.000000 4 [ENTER]
Enter: 4 3 3.000000 + [ENTER]
Enter: 7 3.000000 / [ENTER]
Enter: 0.428571 Q [ENTER]

And here is my 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
#include <cstring>
#include <cstdio>
#include <stack>
#include <iostream>
#include <iomanip>
#include <string>
#include <stdexcept>
#include <stdlib.h>
using namespace std;

bool InputIsGood(string str){
    bool good = true;
    if ((str == "q") || (str == "Q"))good=false;
    return good;
}

int main() 
{
    stack<double>x;
    string token;
    cout << "Enter: ";
    
    do {
    getline(cin,token);
    
        if (isdigit(token[0]))  {
            x.push(atof(token.c_str()));
            cout << "Enter: " << x.top() << " ";
     
        }
        else {
        	double a = x.top();x.pop();
        	double b = x.top();x.pop();
            switch (token[0]) {  
              case '+': x.push(a+b);
                        break;
              case '-': x.push(b-a);
                        break;
              case '*': x.push(b*a);
                        break;
              case '/': x.push(b/a);
                        break;
            }
            cout << "Enter: " << x.top() << " ";
         }
    }while(InputIsGood(token)==true);
return 0;    
}
Feb 24, 2012 at 6:03am
1, at #28, x.top might top all before meeting a math symbol if it's as displayed at your intention.
2, quite not understand how to make "Enter: 4 3 3.000000 + [ENTER]" think it "3+4", not (3.00000+3+4). I guess better record math symbols too.



b2ee
Topic archived. No new replies allowed.