将链接列表的内容写入 txt 文件中
Write content of LinkedList in a txt file.
所以我有以下代码,其中我打印出链表的内容,但是我试图将其写入文件中。我成功地读出了一个文件并创建了链接列表,但现在我陷入了如何将其写回另一个文件的问题。
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);
相关文章:
- 如何将 txt 文件中的行分隔为组件C++
- 无法打开.txt文件
- 如何使用CLion在Mac上创建一个新的.txt文件
- 使用fstream对txt文件中的数字进行循环
- Visual Studio在尝试读取resource.txt文件时崩溃
- 如何从txt文件中读取多个不同长度的数组?
- 在一次迭代中从 txt 文件中读取多行
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 写入超过 1GB 的.txt文件时出现奇怪的行为
- 视觉 如何循环访问C++中遵循类似格式的多个.txt文件?
- txt 文件中浮点数的最大和最小值
- 从.txt文件中读取浮点型数字并在公式中使用它们
- C++将文本从.txt文件解析为变量
- 在树结构.txt文件中搜索节点
- 为什么我无法打开/读取从 Python 调用的 C 扩展名中的 txt 文件?
- 在 txt 文件中显示前两个数字的程序
- 如何从具有两列的.txt文件创建并行数组?
- 如何使用c ++读取带有非英文字母的*.txt文件?(国际化)
- 如何像在 C++ 中处理数组一样对 .txt 文件中的字符进行寻址?
- 如何读取 TXT 文件并仅将 int 存储在 C 中