c++从txt文件中读取数据并存储到链表
时间: 2023-11-27 19:50:45 浏览: 428
可以按照以下步骤实现:
1. 定义一个结构体来存储数据,例如:
```c++
struct Student {
int id;
string name;
int age;
};
```
2. 定义一个链表节点结构体,其中包含一个指向数据结构体的指针和一个指向下一个节点的指针,例如:
```c++
struct ListNode {
Student* data;
ListNode* next;
};
```
3. 定义一个读取文件的函数,例如:
```c++
void readFile(string fileName, ListNode* head) {
ifstream infile(fileName);
if (!infile.is_open()) {
cout << "文件打开失败" << endl;
return;
}
while (!infile.eof()) {
Student* newStudent = new Student;
infile >> newStudent->id >> newStudent->name >> newStudent->age;
ListNode* newNode = new ListNode;
newNode->data = newStudent;
newNode->next = head->next;
head->next = newNode;
}
infile.close();
}
```
4. 在主函数中调用上面的函数,并传入链表头节点。例如:
```c++
int main() {
ListNode* head = new ListNode;
head->next = nullptr;
readFile("student.txt", head);
// 遍历链表并输出数据
ListNode* cur = head->next;
while (cur != nullptr) {
cout << cur->data->id << " " << cur->data->name << " " << cur->data->age << endl;
cur = cur->next;
}
// 释放链表节点和数据结构体的内存
cur = head->next;
while (cur != nullptr) {
head->next = cur->next;
delete cur->data;
delete cur;
cur = head->next;
}
delete head;
return 0;
}
```
注意,上面的代码仅仅是示例代码,实际情况中需要根据具体的需求进行修改。同时,还需要注意内存管理,避免内存泄漏等问题。
阅读全文
相关推荐















