将链接列表的内容写入 txt 文件中

Write content of LinkedList in a txt file.

本文关键字:txt 文件 链接 列表      更新时间:2023-10-16

所以我有以下代码,其中我打印出链表的内容,但是我试图将其写入文件中。我成功地读出了一个文件并创建了链接列表,但现在我陷入了如何将其写回另一个文件的问题。

void LinkedList::printAll()
{
    if(p==NULL)
    {
        cout<<"There are no nodes in the list"<<endl;
        return;
    }
    else
    {
        Node *tmp = p;
        cout<<endl<< "RUID    Name"<<endl;
        while(tmp!=NULL)
        {
            cout <<tmp->ID <<"t"<<tmp->name<<endl;
            tmp=tmp->next;
        }
    }
    cout<<endl;
}

这就是我试图写在文件中而不是打印出来的内容。任何帮助都会很棒。

这就是它应该的样子

鲁伊德名称4325 奥马尔5432 帕尔塔6530 拉尼1034 埃沙2309 拉纳3214 巴德里

需要做的就是将要写入的输出流从cout更改为文件流。

printAll函数的更好方法是这样的:

#include <ostream>
//...
void LinkedList::printAll(std::ostream& os)
{
    if(p==NULL)
    {
        os<<"There are no nodes in the list"<<endl;
        return;
    }
    else
    {
        Node *tmp = p;
        os<<endl<< "RUID    Name"<<endl;
        while(tmp!=NULL)
        {
            os <<tmp->ID <<"t"<<tmp->name<<endl;
            tmp=tmp->next;
        }
    }
    os<<endl;
}

然后,如果我们想打印到控制台:

LinkedList t;
//...
t.printAll(cout);

并打印到文件:

LinkedList t;
//...
std::ofstream ofs("myfile.txt");
t.printAll(ofs);