-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserDataBase.h
More file actions
112 lines (95 loc) · 2.3 KB
/
Copy pathUserDataBase.h
File metadata and controls
112 lines (95 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#pragma once
#include <vector>
#include <algorithm>
#include "User.h"
class UserDatabase {
private:
vector<User> users;
public:
void addUser(const User& user) {
users.push_back(user);
}
User* findUser(const string& username) {
for (User& user : users) {
if (user.getUsername() == username) {
return &user;
}
}
return nullptr; // Return null if user not found
}
int findUserIndex(const string& username) {
for (int i = 0; i < users.size(); i++) {
if (users[i].getUsername() == username) {
return i;
}
}
return -1; // Return -1 if user not found
}
void replaceUser(const string& username, const User& newUser) {
int index = findUserIndex(username);
if (index != -1) {
users[index] = newUser;
}
}
User getUserByIndex(int index) {
if (index >= 0 && index < users.size()) {
return users[index];
}
}
void storeAllUsersToFile(const string& filename) {
ofstream file(filename, ios::app);
clearFileContents(filename);
if (file.is_open()) {
for (const User& user : users) {
file << user.getUsername() << "\n";
file << user.getGame1Highscore() << "\n";
file << user.getPassword() << "\n";
file << user.getCoins() << "\n";
}
file.close();
cout << "All user data stored successfully.\n";
}
else {
cerr << "Unable to open the file.\n";
}
}
void clearFileContents(const std::string& filename) {
std::ofstream ofs;
ofs.open(filename, std::ofstream::out | std::ofstream::trunc);
ofs.close();
}
void loadAllUsersFromFile(const string& filename) {
ifstream file(filename);
if (file.is_open()) {
User tempUser("", 0, 0, 0, "", 0);
while (file >> tempUser) {
users.push_back(tempUser);
cout << "User data loaded successfully.\n";
}
file.close();
}
else {
cerr << "Unable to open the file.\n";
}
}
void subtractCoin(const string& username) {
int index = findUserIndex(username);
if (index != -1) {
users[index].setCoins(users[index].getCoins() - 1);
storeAllUsersToFile("file.txt");
}
}
void addHigscore(const string& username, int score) {
int index = findUserIndex(username);
if (score > users[index].getGame1Highscore())
{
if (index != -1) {
users[index].setGame1Highscore(score);
storeAllUsersToFile("file.txt");
}
}
}
vector<User> getAllUsers() {
return users;
}
};