第1关:增加植物信息
时间: 2023-11-25 22:12:48 浏览: 464
好的,下面是修改后的代码,供您参考:
```c++
#include <bits/stdc++.h>
using namespace std;
// 植物信息定义
struct Plant {
int id; // 植物编号
string name; // 植物名称
string sname; // 学名
string place[100]; // 分布地
string detail; // 详情描述
};
// 链表结点定义
typedef struct LNode {
Plant data; // 结点的数据域
struct LNode* next; // 指针域
} LNode, *LinkList;
// 从文件中读取数据,存入链表L中
void ReadFile(LinkList& L, string filename) {
ifstream fin(filename);
if (fin.is_open()) {
string line;
while (getline(fin, line)) {
// 解析一行数据,创建新结点并添加到链表中
stringstream ss(line);
Plant p;
ss >> p.id >> p.name >> p.sname;
int i = 0;
while (ss >> p.place[i]) {
i++;
}
getline(ss, p.detail);
LNode* node = new LNode;
node->data = p;
node->next = L->next;
L->next = node;
}
fin.close();
}
}
// 判断该植物名称name是否存在于链表中
int InPlant(LinkList L, string name) {
LNode* p = L->next;
int id = 0;
while (p) {
if (p->data.name == name) {
id = p->data.id;
break;
}
p = p->next;
}
return id;
}
// 获取下一个植物的编号
int GetNextId(LinkList L) {
LNode* p = L->next;
int max_id = 0;
while (p) {
if (p->data.id > max_id) {
max_id = p->data.id;
}
p = p->next;
}
return max_id + 1;
}
// 增加植物信息,将该植物的基本信息添加到plant.txt中的最后
// 如果该植物名称存在于plant.txt中,返回false,否则,返回true
bool InsertPlant(LinkList& L, string filename) {
string name, sname, detail;
vector<string> place;
cout << "请输入植物名称:";
cin >> name;
if (InPlant(L, name) > 0) {
cout << "该植物已经存在于plant.txt中!" << endl;
return false;
}
cout << "请输入植物学名:";
cin >> sname;
cout << "请输入植物分布地(以空格分隔):";
string s;
getline(cin, s);
stringstream ss(s);
while (ss >> s) {
place.push_back(s);
}
cout << "请输入植物详情描述:";
getline(cin, detail);
int id = GetNextId(L);
// 将新植物信息添加到文件最后
ofstream fout(filename, ios::app);
if (fout.is_open()) {
fout << id << " " << name << " " << sname << " ";
for (string p : place) {
fout << p << " ";
}
fout << detail << endl;
fout.close();
}
// 在链表中创建新结点
LNode* node = new LNode;
node->data.id = id;
node->data.name = name;
node->data.sname = sname;
copy(place.begin(), place.end(), node->data.place);
node->data.detail = detail;
node->next = L->next;
L->next = node;
cout << "植物信息添加成功!" << endl;
return true;
}
int main() {
LinkList L = new LNode;
L->next = NULL;
string filename = "plant.txt";
ReadFile(L, filename);
while (true) {
cout << "请选择操作(1-增加植物信息,0-退出程序):";
int op;
cin >> op;
if (op == 0) {
break;
}
else if (op == 1) {
InsertPlant(L, filename);
}
else {
cout << "无效操作!" << endl;
}
}
return 0;
}
```