Reputation: 45
I have a constructor and a destructor for a class called StringList. I created functions that add, remove and clear the strings within the linked list. I want this program to retain its added strings even when the program is ended. One way that i can do this is to have my constructor read from a file and my destructor save the strings to that same file. I am brand new into programming and ive been searching how to do this for a linked list but ive hit dead ends so far. The file i read from is called Read.txt, when the destructor is called, all the strings are saved to this file. The Read.txt file contains a list as such:
HELLO
MOM
BART
CART
PETS
Here is the code:
StringList::StringList()
{
ifstream infile;
// i know how to open the file i just dont really have a single clue on how to set each string into the linked list
}
StringList::~StringList()
{
StringListNode *next;
for (StringListNode *sp = pTop; sp != 0; sp = next)
{
next = sp->pNext;
delete sp;
}
}
Any suggestions or examples would be much appreciated. If you need further info or anymore code i wrote, please let me know asap
Upvotes: 0
Views: 2333
Reputation: 905
Here is my suggestion. Hope that can help you.
StringListNode *cur = pTop; // I guess pTop is the head of your list
for each string s // read
{
cur = new StringListNode(s); // call the constructor of StringListNode
cur = cur->pNext;
}
Upvotes: 3
Reputation: 4939
Here is some code to accomplish what you want. For reading, you should have a while loop over the input file stream until no more strings can be read. Add each string using your already written add function. Then for destruction you should open a file stream and save each element of the list accordingly.
StringList::StringList() {
ifstream ifs("MyFilename.txt");
string s;
while(ifs >> s)
Add(s);
}
StringList::~StringList() {
ofstream ofs("MyFilename.txt");
StringListNode *next;
for (StringListNode *sp = pTop; sp != 0; sp = next)
{
ofs << sp->element << endl;
next = sp->pNext;
delete sp;
}
}
Upvotes: 0