#include #include #include #include

using namespace std;

struct Record { string name; int age; string address; };

class Database { private: vector records; string filename;

void saveToFile() {
    ofstream file(filename);
    if (file.is_open()) {
        for (const auto& record : records) {
            file << record.name << "," << record.age << "," << record.address << endl;
        }
        file.close();
        cout << "Database saved to file." << endl;
    } else {
        cout << "Error opening file." << endl;
    }
}

void loadFromFile() {
    ifstream file(filename);
    if (file.is_open()) {
        string line;
        while (getline(file, line)) {
            Record record;
            size_t commaIndex = line.find(",");
            record.name = line.substr(0, commaIndex);
            line = line.substr(commaIndex + 1);
            
            commaIndex = line.find(",");
            record.age = stoi(line.substr(0, commaIndex));
            line = line.substr(commaIndex + 1);
            
            record.address = line;
            
            records.push_back(record);
        }
        file.close();
        cout << "Database loaded from file." << endl;
    } else {
        cout << "Error opening file." << endl;
    }
}

public: Database(const string& filename) : filename(filename) { loadFromFile(); }

void addRecord(const Record& record) {
    records.push_back(record);
    saveToFile();
}

void printRecords() const {
    for (const auto& record : records) {
        cout << "Name: " << record.name << ", Age: " << record.age << ", Address: " << record.address << endl;
    }
}

};

int main() { Database db("data.txt");

Record record1;
record1.name = "John";
record1.age = 25;
record1.address = "123 Main St";
db.addRecord(record1);

Record record2;
record2.name = "Amy";
record2.age = 30;
record2.address = "456 Elm St";
db.addRecord(record2);

db.printRecords();

return 0;
请用c++写一个数据库

原文地址: https://www.cveoy.top/t/topic/h6ST 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录