Skip to content

Commit e097faa

Browse files
authored
Merge pull request #79 from Xtha-Sunil/main
Sample OODB using c++
2 parents a1a7275 + 246443c commit e097faa

1 file changed

Lines changed: 92 additions & 0 deletions

File tree

c++/customOODB.cpp

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
// Sample of Object Oriented Database (OODB) using C++.
2+
3+
#include <iostream>
4+
#include <fstream>
5+
#include <string>
6+
#include <map>
7+
using namespace std;
8+
9+
// Defining the structure of object
10+
class Person {
11+
private:
12+
string name;
13+
int age;
14+
15+
public:
16+
Person() : age(0) {} // Default age 0
17+
Person(string n, int a) : name(n), age(a) {}
18+
19+
string getName() const { return name; }
20+
int getAge() const { return age; }
21+
22+
void save(ofstream& out) const {
23+
out << name << '\n' << age << '\n';
24+
}
25+
26+
void load(ifstream& in) {
27+
getline(in, name);
28+
in >> age;
29+
in.ignore(); // this consumes the leftover newlines
30+
}
31+
32+
void display() const {
33+
cout << "Name: " << name << ", Age: " << age << endl;
34+
}
35+
};
36+
37+
int main() {
38+
// Object to store
39+
Person person1("Alice", 30);
40+
Person person2("Bob", 25);
41+
42+
// concept of key,value to save and retrieve
43+
map<string, Person> db;
44+
db["alice"] = person1;
45+
db["bob"] = person2;
46+
47+
// Simulated DB using file handeling
48+
ofstream outFile("assets/mydatabase.txt");
49+
if (!outFile) {
50+
cerr << "Error opening file for writing." << endl;
51+
return 1;
52+
}
53+
54+
for (auto& entry : db) {
55+
string key = entry.first;
56+
Person& person = entry.second;
57+
58+
outFile << key << '\n';
59+
person.save(outFile);
60+
}
61+
outFile.close();
62+
cout << "Objects saved to database successfully.\n";
63+
64+
// Reading from the DB (txt file)
65+
ifstream inFile("assets/mydatabase.txt");
66+
if (!inFile) {
67+
cerr << "Error opening file for reading." << endl;
68+
return 1;
69+
}
70+
71+
map<string, Person> loadedDb;
72+
while (true) {
73+
string key;
74+
if (!getline(inFile, key)) break;
75+
76+
Person p;
77+
p.load(inFile);
78+
loadedDb[key] = p;
79+
}
80+
inFile.close();
81+
82+
// Display the saved data
83+
cout << "\nRetrieved objects from database:\n";
84+
for (auto& entry : loadedDb) {
85+
string key = entry.first;
86+
Person& person = entry.second;
87+
cout << "Key: " << key << " -> ";
88+
person.display();
89+
}
90+
91+
return 0;
92+
}

0 commit comments

Comments
 (0)