stacks as UNDO function

Hi,

I need to make a simple calculator that just does addition and subtraction. But the program should keep a running total of the calculations entered like this:

sum = 0
12 + 3
sum = 15
5-2
sum = 12
1+1
sum = 13

But it also needs to have an UNDO command which removes the last calculation from the sum as if it never executed. The number of UNDO levels is unlimited, so it is possible to use the UNDO command to UNDO all of the operations back to the initial state of the program.

I have so far the code on how to do the calculations, and I am trying to use stacks as the undo function. I think the stack push method works to put the sum on top, but when I try to use the pop method to remove from the top, I can't get it to output correctly. How can I change that to make it work ?
Thanks

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
102
103
104
105
#include <iostream>
#include <iomanip>
 
using namespace std;
 
#define MAX 50      
 
class stack
{
  private:
    int arr[MAX];  
    int top;      

 
  public:
     stack()         
     {
        top=-1;    
     }
 

     void push(int total) 
     {

        top++;        
        if(top < MAX)
         {
            arr[top]=total;  
         }

         else
         {
            cout<<"STACK FULL"<<endl;
            top--;
         }

     }

	int pop(int total)               
    {
		 if(top==-1)
		 {
            cout<<"STACK IS EMPTY"<<endl;
            return NULL;
		 }
        else
		{
            total = arr [top];	
            arr[top]= NULL;				 
            top--;			
            return total;				
		 }

     }
};

int main() 
{
	stack total;

    int firstNum, secondNum;		// Operands
    char oper;						// Operator
	char undo;
    int  result;                  // Resulting value
    int sum = 0;                  // sum
 
	cout << "press c to input numbers, or press u to undo calculation" << endl << endl;

	while(cin >> undo)
	{
		if (undo =='c')
		{	
			while (cin >> firstNum >> oper >> secondNum)
			{
				 switch (oper) 
				{
					case '+': result = firstNum + secondNum;
							 sum+= result;
							 total.push(sum);
							 break; 
					case '-': result = firstNum - secondNum;
							 sum-= result;
					         total.push(sum);
							 break;
					 default : cout << "Bad operator '" << oper << "'" << endl;
                      continue;  // Start next loop iteration.
				}
 
				 cout << result << endl << endl;
				 cout << "Sum: " << sum << endl << endl;
			}
		}
		else if (undo == 'u')
		{
			sum = total.pop(sum);
			cout << "Sum: " << sum << endl;
		}

    }
 
 
	system("pause");
    return 0;
}
why not use stack in STL.
The function ,"main",is wrong;
Topic archived. No new replies allowed.