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

In my c++ class we created a stack project. I need help adding a string construc

ID: 3554786 • Letter: I

Question

In my c++ class we created a stack project. I need help adding a string constructor that takes a string to a filename. The file contains a series of numbers seperated by a single space, which should be read into the stack.

The constructor should save the filename in the object when it is called with this new constructor.

When the stack is deleted (through function or program termination) the program should check if the filename is set (indicating that the stack object was created using the new ctor). If so, it should re-open the file and overwrite the existing contents with the current contents of the stack.

I have the whole program written, I just need help with the string constructor.

//This is the class decleration. It is contained in a namespace.

class myStackClass {
   private:
       static const int MAX_STACKSIZE = 100;
       int stack[MAX_STACKSIZE];
       int top;
   public:
       myStackClass();
       myStackClass(std::string); // This is the string constructor... is this the correct decleration for string ctor?
       int push(int insertMe);
       int peek(int & num);
       int pop(int & num);
       int capacity();
   };

myStackClass::myStackClass(){ // default ctor
   top = 0;
   stack[top] = 0;

}


myStackClass::myStackClass(string s){ // string ctor I need help with.
   string number = s;

}

Explanation / Answer

//This is the class decleration. It is contained in a namespace.
#include <fstream>

class myStackClass {
   private:
       static const int MAX_STACKSIZE = 100;
       int stack[MAX_STACKSIZE];
       int top;
       bool isFileSet;
       string filename;
   public:
       myStackClass();
       myStackClass(std::string); // This is the string constructor... is this the correct decleration for string ctor?
       ~myStackClass();
       int push(int insertMe);
       int peek(int & num);
       int pop(int & num);
       int capacity();
   };

myStackClass::myStackClass(){ // default ctor
   top = 0;
   stack[top] = 0;
   isFileSet = false;

}


myStackClass::myStackClass(string s){ // string ctor I need help with.
    isFileSet = true;
    filename = s;
    ifstream in(filename);
    top = 0;
    int n=0;
    while(!in.eof()){
        in >> n;
        stack[i] = n;
        top++;
    }
    in.close();
}

~myStackClass(){
    if(isFileSet){
        ofstream of(filename);
        for(int j=top-1; j>=0; j--){
            of << stack[j] << " ";
        }
        of.close();
    }
}

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