请帮我用c++写一个数据库
当然可以帮你写一个简单的数据库。以下是一个使用C++编写的简单数据库示例:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
struct Record {
int id;
std::string name;
std::string email;
};
std::vector<Record> loadDatabase(const std::string& filename) {
std::vector<Record> database;
std::ifstream file(filename);
if (file.is_open()) {
Record record;
while (file >> record.id >> record.name >> record.email) {
database.push_back(record);
}
file.close();
}
return database;
}
void saveDatabase(const std::vector<Record>& database, const std::string& filename) {
std::ofstream file(filename);
if (file.is_open()) {
for (const auto& record : database) {
file << record.id << " " << record.name << " " << record.email << std::endl;
}
file.close();
}
}
void printDatabase(const std::vector<Record>& database) {
for (const auto& record : database) {
std::cout << "ID: " << record.id << ", Name: " << record.name << ", Email: " << record.email << std::endl;
}
}
void addRecord(std::vector<Record>& database, int id, const std::string& name, const std::string& email) {
Record record;
record.id = id;
record.name = name;
record.email = email;
database.push_back(record);
}
void deleteRecord(std::vector<Record>& database, int id) {
for (auto it = database.begin(); it != database.end(); ++it) {
if (it->id == id) {
database.erase(it);
break;
}
}
}
int main() {
std::vector<Record> database = loadDatabase("database.txt");
addRecord(database, 1, "Alice", "alice@example.com");
addRecord(database, 2, "Bob", "bob@example.com");
addRecord(database, 3, "Charlie", "charlie@example.com");
printDatabase(database);
deleteRecord(database, 2);
saveDatabase(database, "database.txt");
return 0;
}
上述代码定义了一个简单的数据库,使用一个std::vector来存储记录。Record结构体定义了每条记录的字段。loadDatabase函数从文件中加载数据库,saveDatabase函数将数据库保存到文件中,printDatabase函数打印数据库内容。addRecord函数用于添加新记录,deleteRecord函数用于删除指定ID的记录。
在main函数中,首先从文件加载数据库,然后添加几条记录并打印数据库内容。接着删除ID为2的记录,并将更新后的数据库保存到文件中。
你可以根据自己的需求进行修改和扩展。这只是一个简单的示例,实际的数据库通常更加复杂
原文地址: https://www.cveoy.top/t/topic/h6uV 著作权归作者所有。请勿转载和采集!