从文件中读取,存储到链表中,然后再次打印到文件中

Read from file, store into linked list then print to file again

本文关键字:文件 打印 然后 存储 读取 链表      更新时间:2023-10-16

我有一个名为StringList的类的构造函数和析构函数。我创建了添加、删除和清除链表中字符串的函数。我希望这个程序即使在程序结束时也能保留其添加的字符串。我可以做到这一点的一种方法是让我的构造函数从一个文件中读取,我的析构函数将字符串保存到同一个文件。我是编程界的新手,我一直在寻找如何做到这一点的链接列表,但到目前为止,我遇到了死胡同。我从中读取的文件名为read.txt,当调用析构函数时,所有字符串都会保存到该文件中。Read.txt文件包含如下列表:

HELLO
MOM
BART
CART
PETS 

这是代码:

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;
    }
}

任何建议或例子都将不胜感激。如果你需要更多的信息或我写的任何代码,请尽快告诉我

这是我的建议。希望能对你有所帮助。

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;
}

这里有一些代码可以实现您想要的。对于读取,您应该在输入文件流上进行while循环,直到无法读取更多字符串为止。使用已编写的Add函数添加每个字符串。然后,对于销毁,您应该打开一个文件流,并相应地保存列表中的每个元素。


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;
    }
}