// Calc.C // (c) Burton Rosenberg 1996 // Small program to write a stack-based calculator #include #include class Node { public: int item ; Node * next ; } ; class List { private: Node * anchor ; public: void init(void) ; void push(int i) ; void print(void) ; int pop(void) ; } ; void List:: init ( void ) { anchor = NULL ; } void List:: push( int i ) { Node * n = new Node ; n->item = i ; n->next = anchor ; anchor = n ; } void List:: print( void ) { Node * n = anchor ; while ( n != NULL ) { cout << n->item << endl ; n = n->next ; } } int List:: pop( void ) { int i ; Node * p ; if ( anchor==NULL) return 0 ; p = anchor ; anchor = anchor->next ; i = p->item ; delete p ; return i ; } enum CMDTYPE { Number, Plus, Minus, Times, Divide, Quit, Error, Nothing } ; CMDTYPE identify( char s[] ) { switch(s[0]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return Number ; case '+': return Plus ; case '-': return Minus ; case '*': return Times ; case '/': return Divide ; case 'q': case 'Q': return Quit ; default : return Error ; } } int value( char s[] ) { return (s[0]-'0') ; } void main() { int a, b ; List myList ; myList.init() ; CMDTYPE c = Nothing ; char inputLine[100] ; while ( c != Quit ) { cin.getline(inputLine, 100) ; switch( c = identify(inputLine) ) { case Number: myList.push(value(inputLine)) ; break ; case Plus: a = myList.pop() ; b = myList.pop() ; cout << "= " << a+b << endl ; myList.push(a+b) ; break ; case Minus: a = myList.pop() ; b = myList.pop() ; cout << "= " << b-a << endl ; myList.push(b-a) ; break ; case Times: a = myList.pop() ; b = myList.pop() ; cout << "= " << a*b << endl ; myList.push(a*b) ; break ; case Divide: a = myList.pop() ; b = myList.pop() ; cout << "= " << a/b << endl ; myList.push(a/b) ; break ; } } }