请用C++实现一个链表,把rating.json文件数据读入到链表中,文件里的每条记录包含如下字段信息,corp,from, to,score,comment, comments, time
时间: 2024-02-26 09:58:11 浏览: 68
用C++程序写一个链表程序
4星 · 用户满意度95%
好的,我会根据您的要求进行回答,不会透露您的任何要求。
以下是C++实现链表并读取rating.json文件数据的代码:
```cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// 定义链表结构体
struct Node {
string corp;
string from;
string to;
int score;
string comment;
int comments;
string time;
Node* next;
};
int main() {
// 打开rating.json文件
ifstream file("rating.json");
if (!file) {
cout << "文件打开失败!" << endl;
return 0;
}
// 定义头结点和当前结点
Node* head = new Node;
Node* current = head;
// 逐行读取文件数据并存入链表
string line;
while (getline(file, line)) {
// 解析每行数据
int index = line.find(',');
string corp = line.substr(1, index - 2);
line = line.substr(index + 1);
index = line.find(',');
string from = line.substr(1, index - 2);
line = line.substr(index + 1);
index = line.find(',');
string to = line.substr(1, index - 2);
line = line.substr(index + 1);
index = line.find(',');
int score = stoi(line.substr(1, index - 1));
line = line.substr(index + 1);
index = line.find(',');
string comment = line.substr(1, index - 2);
line = line.substr(index + 1);
index = line.find(',');
int comments = stoi(line.substr(1, index - 1));
line = line.substr(index + 1);
string time = line.substr(1, line.length() - 3);
// 创建新结点并添加到链表中
Node* node = new Node;
node->corp = corp;
node->from = from;
node->to = to;
node->score = score;
node->comment = comment;
node->comments = comments;
node->time = time;
node->next = nullptr;
current->next = node;
current = node;
}
// 关闭文件
file.close();
// 输出链表数据
current = head->next;
while (current != nullptr) {
cout << current->corp << " "
<< current->from << " "
<< current->to << " "
<< current->score << " "
<< current->comment << " "
<< current->comments << " "
<< current->time << endl;
current = current->next;
}
// 释放链表空间
current = head;
while (current != nullptr) {
Node* next = current->next;
delete current;
current = next;
}
return 0;
}
```
注意,此代码仅供参考,具体实现可能需要根据实际情况进行调整。
阅读全文