Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

My assignment is to Use an instance of stack from to hold string values and impl

ID: 3567563 • Letter: M

Question

My assignment is to Use an instance of stack from to hold string values and implement the same interface as the data type. However, your implementation (class) should throw an exception if an attempt is made to remove a value from an empty stack. This program must compile correctly! I need help with my code, here is what I have so far.

#include <stack>
#include <string>
#include <iostream>

using namespace std;

int main()
{
try
{
   stack<int> values;
   string input;
  
   stack<string> s;
   s.push("a");
   s.push("b");
   s.push("c");
   while (s.size() > 0);
}
    catch (int)
{
cout << "An exception occurred. " << ' ';
{
       cout << s.top() << " ";
       s.pop();
  
      
   }
}

Explanation / Answer

#include <stack>
#include <string>
#include <iostream>

using namespace std;

struct MyException : public exception
{
const char * what () const throw ()
{
    return "Stack Empty Exception";
}
};

int main()
{
    stack<string> s;
try
{
   stack<int> values;
   string input;
int c=0;

   s.push("a");
   s.push("b");
   s.push("c");
   do{
   if(c<s.size()){
   s.pop();c++;}
   else
   throw MyException();}
   while (s.size() > 0);
}
    catch(MyException& e)
{
    std::cout << "MyException caught" <<endl;
    std::cout << e.what() << endl;
}
    
}

o/p:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote