使用c++
实现了一个简单的通讯录:
基本功能为:
person
#include "string"
using namespace std;
struct person {
int id;
string name;
string iphone;
};
static string toString(person p) {
return "{""\"name\":" + p.name + ",""\"iphone\"" + p.iphone + "}";
}
contact
#include <iostream>
#include "person.cpp"
using namespace std;
class contact {
private:
struct person persons[100];
int top = 0;
public:
void run() {
contact contact;
int option;
while (true) {
contact.showMenu();
cin >> option;
contact.input(option);
}
}
void showMenu() {
for (int i = 0; i < 20; ++i) {
cout << "#";
}
cout << endl;
cout << "## 1.添加联系人 ##" << endl;
cout << "## 2.显示联系人 ##" << endl;
cout << "## 3.删除联系人 ##" << endl;
cout << "## 4.查找联系人 ##" << endl;
cout << "## 5.修改联系人 ##" << endl;
cout << "## 6.清空联系人 ##" << endl;
cout << "## 0.退出通讯录 ##" << endl;
for (int i = 0; i < 20; ++i) {
cout << "#";
}
cout << endl;
}
void setName(struct person &p) {
string name;
cout << "input name:" << endl;
cin >> name;
p.name = name;
}
void setIphone(struct person &p) {
string iphone;
cout << "input iphone" << endl;
cin >> iphone;
p.iphone = iphone;
}
void setId(struct person &p) {
p.id = top;
}
// 添加联系人
void add() {
cout << "添加联系人" << endl;
struct person p;
setName(p);
setIphone(p);
setId(p);
persons[top++] = p;
cout << "用户添 " << p.name << " 加成功" << endl;
}
// 展示联系人
void showContact() {
for (int i = 0; i < top; i++) {
cout << persons[i].id << " "
<< persons[i].name << " "
<< persons[i].iphone << " "
<< endl;
}
}
// 删除联系人
void deleteById() {
cout << "input id : " << endl;
int id;
cin >> id;
string jsonStr = toString(persons[id]);
cout << "正在删除: " << jsonStr << endl;
if (id > 1 || id > 100) {
cout
<< "id 不存在" << endl;
}
for (int i = id; i < top - 1; i++) {
persons[i] = persons[i + 1];
}
top--;
cout << "删除成功" << endl;
}
// 搜索联系人
void searchPerson() {
string name;
int num = 0;
cout << "请输入要查找的姓名" << endl;
cin >> name;
for (struct person p: persons) {
if (p.name == name) {
cout << toString(p) << endl;
num++;
}
}
cout << "一共找到: " << num << " 条记录" << endl;
}
// 编辑联系人
void edit() {
int id;
showContact();
cout << "输出需要编辑的ID:" << endl;
cin >> id;
if (id < 0 || id > top) {
cout << "id无效";
return;
}
setName(persons[id]);
setIphone(persons[id]);
cout << "修改成功" << endl;
}
// 清空联系人
void qingkong() {
top = 0;
cout << "已清空联系人" << endl;
}
// 退出系统
void exitContact() {
exit(0);
}
void input(int option) {
switch (option) {
case 1:
add();
break;
case 2:
showContact();
break;
case 3:
deleteById();
break;
case 4:
searchPerson();
break;
case 5:
edit();
break;
case 6:
qingkong();
break;
case 0:
exitContact();
break;
default:
cout << "输入参数不正确" << endl;
}
};
};