我用了链表类的方法来写了一堆数据,那么我该如何将这堆数据存入一个txt文件
时间: 2024-02-11 09:07:49 浏览: 26
如果你已经使用链表类来存储了一堆数据,那么你可以使用文件流来将这些数据写入到一个txt文件中。以下是一个示例代码,可以实现将链表数据写入到txt文件中:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedList {
public:
LinkedList() : head(nullptr) {}
void add(int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
}
void display() {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
void writeToTxt(string fileName) {
ofstream file(fileName);
Node* temp = head;
while (temp != nullptr) {
file << temp->data << endl;
temp = temp->next;
}
file.close();
}
private:
Node* head;
};
int main() {
LinkedList list;
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.display();
list.writeToTxt("data.txt");
return 0;
}
```
在以上示例代码中,我们定义了一个链表类 LinkedList,其中包含了添加数据、展示数据和将数据写入txt文件的三个方法。在 main 函数中,我们创建了一个 LinkedList 类型的对象 list,并向其中添加了一些数据。然后,我们展示了这些数据,并使用 writeToTxt 方法将这些数据写入到了 "data.txt" 文件中。
需要注意的是,在使用文件流写入数据时,需要使用 ofstream 类型的对象,并调用其 << 运算符来写入数据。同时,还需要注意文件的访问权限和路径等问题。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)