#include <iostream>
#include <fstream>
using namespace std;
struct Point
{
int x, y, w;
Point *next;
Point() : x(0), y(0), w(0), next(nullptr) {} // 无参初始化
Point(int x, int y, int w) : x(x), y(y), w(w), next(nullptr) {} // 无参初始化
};
// 选项
enum
{
EXIT,
ADD,
DEL,
UPDATE,
QUERY
};
// 添加
void add(Point *&h, Point *p)
{
Point *p2 = h;
while (p2->next)
{
p2 = p2->next;
}
p2->next = p;
cout << "add successfully" << endl;
}
// 显示
void show(Point *&h)
{
Point *p = h->next;
while (p)
{
cout << p->x << " " << p->y << " " << p->w << endl;
p = p->next;
}
}
// 删除
void del(Point *&h, int tar)
{
// 删除数据
auto *p1 = h;
auto *p2 = h->next;
while (p2)
{
if (p2->x == tar)
{
p1->next = p2->next;
delete p2;
cout << "delete successfully" << endl;
break;
}
p1 = p1->next;
p2 = p2->next;
}
}
// 修改
void update(Point *&h, int u, int ww)
{
// 删除数据
auto *p1 = h->next;
while (p1)
{
if (p1->x == u)
{
p1->w = ww;
cout << "update successfully" << endl;
break;
}
p1 = p1->next;
}
}
// 功能菜单
void menu()
{
cout << "======功能菜单=======" << endl;
cout << "1.添加\n";
cout << "2.删除\n";
cout << "3.修改\n";
cout << "4.显示\n";
cout << "0.退出\n";
cout << "请选择功能:";
}
void read(Point *&h)
{
ifstream fin("data.txt", ios::in);
auto *p = h;
while (!fin.eof())
{
auto p2 = new Point();
fin >> p2->x >> p2->y >> p2->w;
p->next = p2;
p = p2;
while (fin.peek() == '\n')
fin.get();
}
fin.close();
}
void write(Point *&h)
{
ofstream fout("data.txt", ios::out);
auto *p = h->next;
while (p)
{
fout << p->x << " " << p->y << " " << p->w << "\n";
p = p->next;
}
fout.close();
}
int main()
{
Point *h = new Point();
while (true)
{
system("CLS");
read(h);
menu();
int ch;
cin >> ch;
switch (ch)
{
case ADD:
{
add(h, new Point(1, 2, 3));
break;
}
case DEL:
{
del(h, 1);
break;
}
case UPDATE:
{
update(h, 1, 22);
break;
}
case QUERY:
{
show(h);
break;
}
case EXIT:
{
cout << "exit system successfully" << endl;
system("PAUSE");
exit(0);
}
default:
{
cout << "input error! please input again!" << endl;
}
}
system("PAUSE");
write(h);
}
}
基于链表对文件进行增删改查
于 2020-05-27 00:29:12 首次发布