Computer Science 261
Exercise set #5
Due: Thursday, Oct. 21
Two parts. As with exercise #4, writing the routines will be useful review for the exam Friday.
Consider the following class definition and main routine:
#include <iostream.h>
const int StackSize = 15;
class IntStack{
public:
// Constructor / destructor
IntStack()
{
theStack = new int[StackSize];
TOS = 0;
}
~IntStack()
{
delete [] theStack;
TOS = 0;
}
//
// You will need to change the constructor and destructor
// when you change this to a linked list implementation.
// Accessor functions
void Push(int theArgument);
int Pop();
bool IsEmpty();
bool IsFull();
private:
int *theStack;
int TOS;
};
int main()
//
// A simple calculator. Uses cin.get and cin.putback
//
{
IntStack MyStack;
int temp1, temp2;
char ch;
cout << endl << "Simple RPN calculator. End with ';'" << endl;
cin.get(ch); // Get the first character
while ((ch == ' ') || (ch == '\n')) // Skip over "noise" (blanks and
// newlines
cin.get(ch);
while (ch != ';')
{
switch (ch) {
case '+' : {
temp1 = MyStack.Pop();
temp2 = MyStack.Pop();
MyStack.Push(temp2 + temp1);
break;
}
case '-' : {
temp1 = MyStack.Pop();
temp2 = MyStack.Pop();
MyStack.Push(temp2 - temp1);
break;
}
case '*' : {
temp1 = MyStack.Pop();
temp2 = MyStack.Pop();
MyStack.Push(temp2 * temp1);
break;
}
case '/' : {
temp1 = MyStack.Pop();
temp2 = MyStack.Pop();
MyStack.Push(temp2 / temp1);
break;
}
default : { // assume that ch is the start of an integer number
cin.putback(ch);
cin >> temp1;
cout << "\nPushing value " << temp1 << endl;
MyStack.Push(temp1);
break;
}
} // end of switch
cin.get(ch); // Get the next character
while ((ch == ' ') || (ch == '\n')) //Skip over noise. This could be written
// as a 'GetNextCharacter' routine.
cin.get(ch);
}
cout << "\nDone! The result of your calculations is : ";
cout << MyStack.Pop();
cout << endl;
return 0;
}
In both cases, test your program using the main program provided (a simple calculator using the integer stack. Take particular note of the use of cin.get and cin.putback.