Created
August 3, 2023 09:12
-
-
Save M0nteCarl0/65cbc4254c319cd8aa6e5ca7191321b7 to your computer and use it in GitHub Desktop.
HistoryManager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <vector> | |
#include <nlohmann/json.hpp> | |
using namespace std; | |
using json = nlohmann::json; | |
struct HistoryEntry { | |
std::string action; | |
std::string timestamp; | |
}; | |
class HistoryManager { | |
private: | |
std::vector<HistoryEntry> history; | |
std::string filename; | |
size_t maxSize; | |
public: | |
HistoryManager(const std::string& filename, size_t maxSize) | |
: filename(filename), maxSize(maxSize) {} | |
void addEntry(const HistoryEntry& entry) { | |
history.push_back(entry); | |
if (history.size() > maxSize) { | |
history.erase(history.begin()); | |
} | |
} | |
void saveToFile() { | |
json jsonHistory; | |
for (const auto& entry : history) { | |
json jsonEntry; | |
jsonEntry["action"] = entry.action; | |
jsonEntry["timestamp"] = entry.timestamp; | |
jsonHistory.push_back(jsonEntry); | |
} | |
std::ofstream file(filename); | |
file << jsonHistory.dump(4); | |
file.close(); | |
} | |
void loadFromFile() { | |
std::ifstream file(filename); | |
if (file.is_open()) { | |
json jsonHistory; | |
file >> jsonHistory; | |
history.clear(); | |
for (const auto& jsonEntry : jsonHistory) { | |
HistoryEntry entry; | |
entry.action = jsonEntry["action"]; | |
entry.timestamp = jsonEntry["timestamp"]; | |
history.push_back(entry); | |
} | |
file.close(); | |
} else { | |
std::cout << "Error: Failed to open file" << std::endl; | |
} | |
} | |
void displayHistory() { | |
if (history.empty()) { | |
std::cout << "No history entries found." << std::endl; | |
} else { | |
std::cout << "History Entries:" << std::endl; | |
for (const auto& entry : history) { | |
std::cout << "Action: " << entry.action << std::endl; | |
std::cout << "Timestamp: " << entry.timestamp << std::endl; | |
std::cout << std::endl; | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment