Question

In: Computer Science

Write a program that implements a stack of integers, and exercises the stack based on commands...

Write a program that implements a stack of integers, and exercises the stack based on commands read from cin. To do this, write a class called Stack with exactly the following members:

class Stack {
    public:
        bool isEmpty();
        // returns true if stack has no elements stored

        int top();
        // returns element from top of the stack
        // throws runtime_error("stack is empty")

        int pop();
        // returns element from top of the stack and removes it
        // throws runtime_error("stack is empty")

        void push(int);
        // puts a new element on top of the stack

    private:
        vector<int> elements;
};

The program should read commands from cin until either end-of-file is reached or the command end is entered. (You can manually test for end-of-file by entering CTRL-D.) Each time the program expects a new command it should first print a prompt: "stack> "

Your program should catch all errors that happen and continue execution until the end command or end-of-file.

In case the command push is read, the program should read an integer value from cin and push it onto the stack. In case top is read, the program should print the top integer of the stack to cout. In case pop is read, the program should print the top integer of the stack to cout, and remove it from the stack. In case the command list is read, the program should print all values currently on the stack, without modifying the stack. (Exact format see below.)

Your program should check whether a "number" to be pushed is actually a number. If not, print an error message (see below), and reset cin such that it will again accept commands. (See Section 7.6 of the zyBook.) Also, your program should ignore all characters behind a number to be pushed that are on the same input line (example see below).

An example of a correct execution of this program is shown below:

stack> push 5
stack> pop
5
stack> pop 
error: stack is empty
stack> push 6
stack> push 4bb
stack> push foo
error: not a number
stack> list
[4,6]
stack> list
[4,6]
stack> top
4
stack> hello
error: invalid command 
stack> end 

You may want to use the compare() function (Links to an external site.) on a string to check which command has been entered.

Use of arrays, a built-in stack class, or container classes from std:: other than vector, is not allowed.

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

#include<iostream>

#include<vector>

#include<stdexcept>

#include<string>

#include<limits> //for clearing input buffer on errors

using namespace std;

class Stack {

    public:

        bool isEmpty();

        // returns true if stack has no elements stored

        int top();

        // returns element from top of the stack

        // throws runtime_error("stack is empty")

        int pop();

        // returns element from top of the stack and removes it

        // throws runtime_error("stack is empty")

        void push(int);

        // puts a new element on top of the stack

    private:

        vector<int> elements;

};

//implementation of all methods

bool Stack::isEmpty(){

                //stack is empty if internal vector is empty

                return elements.empty();

}

int Stack::top(){

                //if empty, throwing exception

                if(isEmpty()){

                                throw runtime_error("stack is empty");

                }

                //returning last element

                return elements[elements.size()-1];

}

int Stack::pop(){

                //if empty, throwing exception

                if(isEmpty()){

                                throw runtime_error("stack is empty");

                }

                //getting last element

                int i=elements[elements.size()-1];

                //removing it

                elements.pop_back();

                //returning it

                return i;

}

void Stack::push(int element){

                //simply adding to the end

                elements.push_back(element);

}

//method to clear the input buffer upto the next newline character

void clear_input(){

                //clearing buffer

                cin.clear();

                //removing characters upto new line from stdin

                cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

}

//method to print a stack without modifying it

void print_stack(Stack s){

                //creating a temporary stack

                Stack temp;

                cout<<"[";

                //looping until s is empty

                while(!s.isEmpty()){

                                //removing top element, pushing to temp and displaying it

                                int i=s.pop();

                                temp.push(i);

                                cout<<i;

                                //printing a comma if this is not last element

                                if(!s.isEmpty()){

                                               cout<<",";

                                }

                }

                cout<<"]"<<endl;

                //now popping from temp and pushing to s, so that the original stack is left unchanged.

                while(!temp.isEmpty()){

                                s.push(temp.pop());

                }

}

int main(){

                //creating a stack

                Stack stk;

                string commmand;

                int temp;

                cout<<"stack> ";

                //looping until eof is met or end is entered

                while(cin>>commmand){

                                //comparing input command to each valid commands

                                if(commmand.compare("push")==0){

                                               //reading input

                                               cin>>temp;

                                               //displaying error in case of error

                                               if(!cin.good()){

                                                               cout<<"error: not a number"<<endl;

                                               }else{

                                                               //pushing to stack

                                                               stk.push(temp);

                                               }

                                }else if(commmand.compare("pop")==0){

                                               //displaying error if stack is empty

                                               if(stk.isEmpty()){

                                                               cout<<"error: stack is empty"<<endl;

                                               }else{

                                                               //removing and displaying top element

                                                               cout<<stk.pop()<<endl;

                                               }

                                }else if(commmand.compare("top")==0){

                                               //displaying error if stack is empty

                                               if(stk.isEmpty()){

                                                               cout<<"error: stack is empty"<<endl;

                                               }else{

                                                               //displaying top element

                                                               cout<<stk.top()<<endl;

                                               }

                                }else if(commmand.compare("list")==0){

                                               //printing stack

                                               print_stack(stk);

                                }else if(commmand.compare("end")==0){

                                               //exiting loop

                                               break;

                                }else{

                                               //anything else is invalid

                                               cout<<"error: invalid command"<<endl;

                                }

                                //clearing input upto newline to prevent multiple command entry at once and also to

                                //prevent the infinite loop caused by invalid input when the system is expecting

                                //numeric input

                                clear_input();

                                //displaying prompt for next command

                                cout<<"stack> ";

                }

                return 0;

}

/*OUTPUT*/

stack> push 5

stack> pop

5

stack> pop

error: stack is empty

stack> push 6

stack> push 4jhjef

stack> push xhd

error: not a number

stack> list

[4,6]

stack> list

[4,6]

stack> top

4

stack> end


Related Solutions

Implementing a Stack Write a program that implements a stack of integers, and exercises the stack...
Implementing a Stack Write a program that implements a stack of integers, and exercises the stack based on commands read from cin. To do this, write a class called Stack with exactly the following members: class Stack { public: bool isEmpty(); // returns true if stack has no elements stored int top(); // returns element from top of the stack // throws runtime_error("stack is empty") int pop(); // returns element from top of the stack and removes it // throws...
Write a program in C++ that efficiently implements a skip list that holds integers. Your program...
Write a program in C++ that efficiently implements a skip list that holds integers. Your program should: 1. Accurately implement the skip list ADT using a random number generator and nodes that contain an integer as well as the addresses of adjacent nodes to the left, right, up, and down. 2. Correctly implement the Insert, Search, and Delete operations. 3. Read a series of unique, newline-delineated integers from a file and insert them (one at a time in the order...
Write a program to implement the IntStack that stores a static stack of integers and performs...
Write a program to implement the IntStack that stores a static stack of integers and performs the pop, push, isFull, and isEmpty operations. Write the main class to create a static stack of numbers 10, 20, 30, 40, and 50 then try the member functions. C++
Write a program to implement the IntStack that stores a static stack of integers and performs...
Write a program to implement the IntStack that stores a static stack of integers and performs the pop, push, isFull, and isEmpty operations. Write the main class to create a static stack of numbers 10, 20, 30, 40, and 50 then try the member functions. C++
write a c++ program to perform the following operations on stack of Integers (Array Implementation of...
write a c++ program to perform the following operations on stack of Integers (Array Implementation of Stack with maximum size MAX) (i) Push an Element on to stack (ii) Pop an Element from stack (iii) Demonstrate how stack can be used to check Palindrome (iv) Display the status of stack (v) Exit
The program (​ stack-ptr.c​ ) implements stack using a linked list, however, it contains a race...
The program (​ stack-ptr.c​ ) implements stack using a linked list, however, it contains a race condition and is not appropriate for a concurrent environment. Using Pthreads mutex locks, fix the race condition. For reference, see Section 7.3.1 of SGG book.(Section 7.3.1 is about mutex and semaphores it does explain how to implement I'm just having a hard time finding the race condition within the code) /* * Stack containing race conditions */ #include #include #include typedef int value_t; //...
In an application write a method filterStack that takes a stack of integers as a parameter...
In an application write a method filterStack that takes a stack of integers as a parameter and filters its elements (in a new Stack) in a way that places the even elements at the bottom and the odd ones at the top. The original stack should remain unchanged. You should use a queue (only one queue) as a temporary storage. Use stack and queue operations only to solve this problem. No need to write the main method. For example, if...
/** * Write a recursive function that accepts a stack of integers and * replaces each...
/** * Write a recursive function that accepts a stack of integers and * replaces each int with two copies of that integer. For example, * calling repeatStack and passing in a stack of { 1, 2, 3} would change * the stack to hold { 1, 1, 2, 2, 3, 3}. Do not use any loops. Do not use * any data structures other than the stack passed in as a parameter. * @param stack */ public static void...
Solve this Write a C++ class that implements a stack using a linked list. The type...
Solve this Write a C++ class that implements a stack using a linked list. The type of data contained in the stack should be double. The maximum size of the stack is 30. Implement the following methods: . · Constructor and destructor; // 5 pts · void push (double value); // pushes an element with the value into the stack. 5 pts. · double pop (); // pops an element from the stack and returns its value. 5 pts. ·...
Exercise 3: Stack Write a program in Java to manipulate a Stack List: 1. Create Stack...
Exercise 3: Stack Write a program in Java to manipulate a Stack List: 1. Create Stack List 2. Display the list 3. Create the function isEmply 4. Count the number of nodes 5. Insert a new node in the Stack List. 6. Delete the node in the Stack List. 7. Call all methods above in main method with the following data: Test Data : Input the number of nodes : 4 Input data for node 1 : 5 Input data...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT