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

时间:2013-07-16 03:53:41

标签: c++ linked-list

我有一个名为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;
    }
}

非常感谢任何建议或示例。如果您需要更多信息或我编写的代码,请尽快告诉我

2 个答案:

答案 0 :(得分:3)

这是我的建议。希望能帮到你。

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

答案 1 :(得分:0)

这是一些完成你想要的代码。对于读取,您应该在输入文件流上有一个while循环,直到不再能读取字符串。使用已编写的添加函数添加每个字符串。然后,为了销毁,您应该打开一个文件流并相应地保存列表的每个元素。


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