diff options
16 files changed, 1350 insertions, 0 deletions
| -rw-r--r-- | Utills/Kindle/Book.cpp | 174 | ||||
| -rw-r--r-- | Utills/Kindle/Book.h | 34 | ||||
| -rw-r--r-- | Utills/Kindle/Kindle.cpp | 354 | ||||
| -rw-r--r-- | Utills/Kindle/Kindle.h | 55 | ||||
| -rw-r--r-- | Utills/Kindle/Page.cpp | 37 | ||||
| -rw-r--r-- | Utills/Kindle/Page.h | 21 | ||||
| -rw-r--r-- | Utills/Kindle/Pair.hpp | 29 | ||||
| -rw-r--r-- | Utills/Kindle/Source.cpp | 6 | ||||
| -rw-r--r-- | Utills/Kindle/User.cpp | 22 | ||||
| -rw-r--r-- | Utills/Kindle/User.h | 22 | ||||
| -rw-r--r-- | Utills/Kindle/readme.md | 66 | ||||
| -rw-r--r-- | Utills/Kindle/serialize.cpp | 71 | ||||
| -rw-r--r-- | Utills/Kindle/serialize.h | 20 | ||||
| -rw-r--r-- | Utills/Kindle/string.cpp | 158 | ||||
| -rw-r--r-- | Utills/Kindle/string.h | 42 | ||||
| -rw-r--r-- | Utills/Kindle/vector.hpp | 239 |
diff --git a/Utills/Kindle/Book.cpp b/Utills/Kindle/Book.cpp new file mode 100644 index 0000000..8bfb050 --- /dev/null +++ b/Utills/Kindle/Book.cpp @@ -0,0 +1,174 @@ +#include "Book.h"
+#include<iostream>
+
+void Book::addRating(unsigned short r, const string& name) {
+ if (r > 10)
+ return;
+
+ int raterIndex = -1;
+
+ for (size_t i = 0; i < ratings.getSize(); i++) {
+ if (name == ratings[i].getFirst()) {
+ raterIndex = i;
+ break;
+ }
+ }
+
+ if (raterIndex != -1)
+ ratings[raterIndex].setSecond(r);
+ else {
+ Pair<string, unsigned> toPush(name, r);
+ ratings.pushBack(std::move(toPush));
+ }
+}
+
+void Book::print() const {
+ std::cout << title << " by: " << author << std::endl;
+}
+
+Book::Book(const string& pAuthor, const string& pTitle) {
+ author = pAuthor;
+ title = pTitle;
+}
+
+void Book::writeToFile(std::ofstream& outFile) const {
+ writeString(outFile, author); // Author
+ writeString(outFile, title); // Title
+
+ // Write pages to file
+ int len = data.getSize();
+ outFile.write((const char*)&len, sizeof(len));
+
+ for (size_t i = 0; i < len; i++)
+ data[i].writeToFile(outFile);
+
+ // Write comments to file:
+ int commentsLen = comments.getSize();
+ outFile.write((const char*)&commentsLen, sizeof(commentsLen));
+ for (size_t i = 0; i < commentsLen; i++)
+ writeCommentsToFile(outFile, comments[i]);
+
+ // Write rates to file:
+ int ratesCount = this->ratings.getSize();
+ outFile.write((const char*)&ratesCount, sizeof(ratesCount));
+ for (size_t i = 0; i < ratesCount; i++)
+ writeRatesToFile(outFile, ratings[i]);
+}
+
+void Book::readFromFile(std::ifstream& inFile) {
+ author = readString(inFile); // Author
+ title = readString(inFile); // Title
+
+ // Read pages:
+ int len = 0;
+ inFile.read((char*)&len, sizeof(len));
+
+ for (size_t i = 0; i < len; i++) {
+ data.pushBack(Page());
+ data[i].readFromFile(inFile);
+ }
+
+ // Read comments
+ int commentsLen = 0;
+ inFile.read((char*)&commentsLen, sizeof(commentsLen));
+
+ for (size_t i = 0; i < commentsLen; i++) {
+ Pair<string, string> toInsert = readCommentsFromFile(inFile);
+ comments.pushBack(std::move(toInsert));
+ }
+
+ // Read rates from file
+ int ratesCount = 0;
+ inFile.read((char*)&ratesCount, sizeof(ratesCount));
+ for (size_t i = 0; i < ratesCount; i++) {
+ Pair<string, unsigned> toPush = readRatesFromFile(inFile);
+ ratings.pushBack(std::move(toPush));
+ }
+}
+
+double Book::getAvarageRating() const {
+ double sum = 0;
+ for (size_t i = 0; i < ratings.getSize(); i++)
+ sum += ratings[i].getSecond();
+
+ return sum / (double)(ratings.getSize());
+}
+
+void Book::write(unsigned pagesCount) {
+ unsigned short lines = 0;
+
+ for (int i = 0; i < pagesCount; i++) {
+ std::cout << "Enter lines in page " << i + 1 << ": ";
+ std::cin >> lines;
+ std::cin.ignore();
+ Page toInsert;
+
+ toInsert.write(lines);
+
+ data.pushBack(std::move(toInsert));
+ }
+}
+
+void Book::displayBook() const {
+ bool reading = true;
+ bool displayMenu = true;
+ unsigned pageNumber = 0;
+
+ char cmd = '\0';
+ unsigned pageIndex = 0;
+
+ while (reading) {
+ system("cls");
+ if (displayMenu)
+ displayHelpMenu();
+
+ data[pageIndex].displayPage();
+
+ std::cin.get(cmd);
+
+ switch (cmd) {
+ case 'n':
+ if (pageIndex < data.getSize() - 1)
+ pageIndex++;
+ break;
+ case 'p':
+ if (pageIndex > 0)
+ pageIndex--;
+ break;
+ case 'h':
+ displayMenu = !displayMenu;
+ break;
+ case 'q':
+ reading = false;
+ break;
+ case '@':
+ std::cin >> pageNumber;
+ if (pageNumber >= 1 && pageNumber < data.getSize() + 1)
+ pageIndex = pageNumber - 1;
+ break;
+ default:
+ break;
+ }
+ }
+ system("cls");
+}
+
+void Book::showComments() const {
+ for (size_t i = 0; i < comments.getSize(); i++)
+ std::cout << comments[i].getFirst() << " wrote: " << comments[i].getSecond() << std::endl;
+}
+
+void Book::showRates() const {
+ for (size_t i = 0; i < ratings.getSize(); i++)
+ std::cout << ratings[i].getFirst() << ": " << ratings[i].getSecond() << " start" << std::endl;
+ std::cout << std::endl;
+
+ std::cout << "Avarage rate: " << getAvarageRating() << std::endl;
+}
+
+void Book::displayHelpMenu() const {
+ std::cout << "Entered reader mode." << std::endl
+ << "Press n for next, p for prev." << std::endl <<
+ "Press @ + <number> to go to that page" << std::endl <<
+ "Press h to hide or show this menu or q to exit" << std::endl;
+}
diff --git a/Utills/Kindle/Book.h b/Utills/Kindle/Book.h new file mode 100644 index 0000000..29c4f13 --- /dev/null +++ b/Utills/Kindle/Book.h @@ -0,0 +1,34 @@ +#pragma once
+#include"vector.hpp"
+#include"Page.h"
+#include"Pair.hpp"
+#include"serialize.h"
+
+class Book {
+private:
+ string author;
+ string title;
+ Vector<Pair<string, unsigned>> ratings; // User name + rate
+ Vector<Page> data; // Pages
+ Vector<Pair<string, string>> comments; // commenter's name + comment
+
+ void addRating(unsigned short r, const string& name);
+
+ void write(unsigned pagesCount);
+ void displayBook() const;
+
+ void showComments() const;
+ void showRates() const;
+ void print() const;
+ void displayHelpMenu() const;
+public:
+ Book() {}
+ Book(const string& author, const string& title);
+
+ void writeToFile(std::ofstream& outFile) const;
+ void readFromFile(std::ifstream& inFile);
+ double getAvarageRating() const;
+
+ friend class Kindle;
+};
+
diff --git a/Utills/Kindle/Kindle.cpp b/Utills/Kindle/Kindle.cpp new file mode 100644 index 0000000..84477d2 --- /dev/null +++ b/Utills/Kindle/Kindle.cpp @@ -0,0 +1,354 @@ +#include "Kindle.h"
+
+void Kindle::displayUserDialog(User& currentUser) {
+ std::cout << "Wellcome, " << currentUser.name << std::endl;
+ string cmd;
+
+ while (!(cmd == "exit")) {
+ std::cout << "> ";
+ std::cin >> cmd;
+ if (cmd == "read") {
+ readBookDialog(currentUser);
+ }
+ else if (cmd == "rate") {
+ rateBookDialog(currentUser);
+ }
+ else if (cmd == "comment") {
+ commentOnBookDialog(currentUser);
+ }
+ else if (cmd == "write") {
+ writeBookDialog(currentUser);
+ }
+ else if (cmd == "comments") {
+ displayCommentsDialog();
+ }
+ else if (cmd == "view") {
+ viewBooks();
+ }
+ else if (cmd == "rates") {
+ displayRatesDialog();
+ }
+ }
+
+ std::cout << "Exit user dialog" << std::endl;
+}
+
+void Kindle::saveFileDialog() const {
+ string path;
+ std::cout << "Enter path: ";
+ std::cin >> path;
+ saveToFile(path.c_str());
+}
+
+void Kindle::readFileDialog() {
+ std::cout << "Enter path: ";
+ string path;
+ std::cin >> path;
+ readFromFile(path.c_str());
+}
+
+void Kindle::showHelpDialog() const {
+ std::cout << "Write one of the following commands and press enter: " << std::endl
+ << "| login | signup | load | saveas | view | exit" << std::endl <<
+ "Press any key to exit" << std::endl;
+ std::cin.get();
+
+ std::cin.clear();
+ std::cin.ignore(255, '\n');
+}
+
+void Kindle::saveToFile(const char* filePath) const {
+ std::ofstream outFile(filePath, std::ios::binary);
+
+ if (!outFile)
+ return;
+
+ outFile.write("#Ty", 4);
+
+ size_t sizeOfLib = lib.getSize();
+ size_t sizeOfUsers = users.getSize();
+ // Write lib:
+ outFile.write((const char*)&sizeOfLib, sizeof(sizeOfLib));
+
+ for (size_t i = 0; i < sizeOfLib; i++)
+ lib[i].writeToFile(outFile);
+
+ // Save users:
+ outFile.write((const char*)&sizeOfUsers, sizeof(sizeOfUsers));
+
+ for (size_t i = 0; i < sizeOfUsers; i++)
+ users[i].writeToFile(outFile);
+
+ std::cout << "Saving success!" << std::endl;
+}
+
+void Kindle::readFromFile(const char* filePath) {
+ std::ifstream inFile(filePath, std::ios::binary);
+
+ if (!inFile) {
+ std::cout << "File does not exist" << std::endl;
+ return;
+ }
+
+ char typeChecker[4];
+ inFile.read(typeChecker, 4);
+ if (strcmp(typeChecker, "#Ty") != 0) {
+ std::cout << "Invalid file type" << std::endl;
+ return;
+ }
+
+ size_t sizeOfLib = 0;
+ size_t sizeOfUsers = 0;
+
+ // Read lib
+ inFile.read((char*)&sizeOfLib, sizeof(sizeOfLib));
+
+ for (size_t i = 0; i < sizeOfLib; i++) {
+ lib.pushBack(Book());
+ lib[i].readFromFile(inFile);
+ }
+
+ // Read users:
+ inFile.read((char*)&sizeOfUsers, sizeof(sizeOfUsers));
+
+ for (size_t i = 0; i < sizeOfUsers; i++) {
+ users.pushBack(User());
+ users[i].readFromFile(inFile);
+ }
+
+ std::cout << "Reading success!" << std::endl;
+}
+
+int Kindle::findBookIndex(const string& name) const {
+ for (size_t i = 0; i < lib.getSize(); i++)
+ if (name == lib[i].title)
+ return i;
+ return -1;
+}
+
+int Kindle::findUserIndex(const string& name) const {
+ for (size_t i = 0; i < users.getSize(); i++)
+ if (name == users[i].name)
+ return i;
+ return -1;
+}
+
+bool Kindle::userReadTheBook(const User& currentUser, int bookIndex) const {
+ for (size_t i = 0; i < currentUser.indexesOfBooksRead.getSize(); i++)
+ if (currentUser.indexesOfBooksRead[i] == bookIndex)
+ return true;
+ return false;
+}
+
+bool Kindle::existUser(const string& userName) const {
+ for (size_t i = 0; i < users.getSize(); i++)
+ if (userName == users[i].name)
+ return true;
+ return false;
+}
+
+void Kindle::readBookDialog(User& reader) {
+ std::cout << "Which book would you like to read: ";
+ string bookName;
+ std::cin.ignore();
+ bookName.getLine(std::cin);
+
+ int indexOfBook = findBookIndex(bookName);
+ if (indexOfBook == -1) {
+ std::cout << "No such book" << std::endl;
+ return;
+ }
+ if (!(reader.name == lib[indexOfBook].author) && !userReadTheBook(reader, indexOfBook))
+ reader.indexesOfBooksRead.pushBack(indexOfBook);
+
+ lib[indexOfBook].displayBook();
+}
+
+void Kindle::rateBookDialog(const User& rater) {
+ std::cout << "Enter a book you'd line to rate: ";
+ string bookName;
+ std::cin.ignore();
+ bookName.getLine(std::cin);
+
+ int bookIndex = findBookIndex(bookName);
+
+ if (bookIndex == -1) {
+ std::cout << "No such book" << std::endl;
+ return;
+ }
+
+ if (rater.name == lib[bookIndex].author) {
+ std::cout << "You can't rate your own book" << std::endl;
+ return;
+ }
+
+ unsigned short rate = 0;
+ std::cout << "Enter rate: ";
+ std::cin >> rate;
+
+ lib[bookIndex].addRating(rate, rater.name);
+}
+
+void Kindle::commentOnBookDialog(const User& commenter) {
+ std::cout << "Enter a book you would like to comment: ";
+ string bookName;
+ std::cin.ignore();
+ bookName.getLine(std::cin);;
+
+ int index = findBookIndex(bookName);
+
+ if (index == -1) {
+ std::cout << "No such book";
+ return;
+ }
+
+ std::cout << "Enter comment: ";
+ string comment;
+ comment.getLine(std::cin);
+ if (commenter.name == lib[index].author || userReadTheBook(commenter, index)) {
+ Pair<string, string> toAdd(commenter.name, std::move(comment));
+ lib[index].comments.pushBack(std::move(toAdd));
+ }
+ else {
+ std::cout << "You havent read the book" << std::endl;
+ return;
+ }
+}
+
+void Kindle::writeBookDialog(User& writer) {
+ std::cout << "Enter title: ";
+ string title;
+
+ std::cin.ignore();
+
+ title.getLine(std::cin);
+
+ Book toAdd(writer.name, title);
+
+ std::cout << "Enter pages count: ";
+ unsigned pagesCount = 0;
+ std::cin >> pagesCount;
+
+ std::cin.ignore();
+
+ toAdd.write(pagesCount);
+ writer.indexesOfBooksWritten.pushBack(lib.getSize());
+ lib.pushBack(std::move(toAdd));
+}
+
+void Kindle::displayCommentsDialog() const {
+ std::cout << "Enter book name: ";
+ string bookName;
+ std::cin.ignore();
+ bookName.getLine(std::cin);;
+
+ int indexOfBook = findBookIndex(bookName);
+
+ if (indexOfBook == -1) {
+ std::cout << "No such book" << std::endl;
+ return;
+ }
+
+ lib[indexOfBook].showComments();
+}
+
+void Kindle::displayRatesDialog() const {
+ std::cout << "Enter book name: ";
+ string bookName;
+ std::cin.ignore();
+ bookName.getLine(std::cin);
+
+ int indexOfBook = findBookIndex(bookName);
+
+ if (indexOfBook == -1) {
+ std::cout << "No such book" << std::endl;
+ return;
+ }
+
+ lib[indexOfBook].showRates();
+}
+
+void Kindle::viewBooks() const {
+ for (size_t i = 0; i < lib.getSize(); i++)
+ lib[i].print();
+}
+
+void Kindle::displayLoginDialog() {
+ std::cout << "Enter user name: ";
+ string userName;
+
+ std::cin.ignore();
+
+ userName.getLine(std::cin);
+
+ int userIndex = findUserIndex(userName);
+
+ if (userIndex == -1) {
+ std::cout << "This user does not exist in our system\n";
+ return;
+ }
+ string pwd;
+ std::cout << "Enter password: ";
+
+ pwd.getLine(std::cin);
+
+ if (!(pwd == users[userIndex].password)) {
+ std::cout << "Incorrect password.\n";
+ return;
+ }
+
+ displayUserDialog(users[userIndex]);
+}
+
+void Kindle::displaySignupDialog() {
+ std::cout << "Enter name: ";
+ string name;
+
+ std::cin.ignore();
+
+ name.getLine(std::cin);
+
+ if (existUser(name)) {
+ std::cout << "User with that name already exist!" << std::endl;
+ return;
+ }
+
+ std::cout << "Enter password: ";
+ string password;
+ password.getLine(std::cin);
+
+ User toAdd(name, password);
+ users.pushBack(std::move(toAdd));
+ std::cout << "Successful!" << std::endl;
+}
+
+
+void Kindle::display() {
+ string cmd;
+ while (!(cmd == "exit")) {
+ std::cout << "> ";
+ std::cin >> cmd;
+
+ if (cmd == "login" || cmd == "log in") {
+ displayLoginDialog();
+ }
+ else if (cmd == "signup" || cmd == "sign up") {
+ displaySignupDialog();
+ }
+ else if (cmd == "view") {
+ viewBooks();
+ }
+ else if (cmd == "load") {
+ readFileDialog();
+ }
+ else if (cmd == "save") {
+ saveFileDialog();
+ }
+ else if (cmd == "help") {
+ showHelpDialog();
+ }
+ else {
+ std::cout << "Invalid command!" << std::endl;
+ }
+ }
+}
diff --git a/Utills/Kindle/Kindle.h b/Utills/Kindle/Kindle.h new file mode 100644 index 0000000..79bcbd3 --- /dev/null +++ b/Utills/Kindle/Kindle.h @@ -0,0 +1,55 @@ +#pragma once
+#include"vector.hpp"
+#include"Book.h"
+#include"User.h"
+#include"Pair.hpp"
+#include<iostream>
+#include<cstring>
+#include<fstream>
+
+class Kindle {
+private:
+ Vector<Book> lib;
+ Vector<User> users;
+
+ // Helper functions
+ int findBookIndex(const string& name) const;
+ int findUserIndex(const string& name) const;
+
+ // did user read the book?
+ bool userReadTheBook(const User& currentUser, int bookIndex) const;
+
+ // does user exist?
+ bool existUser(const string& userName) const;
+
+ // Functions used by user
+ void readBookDialog(User& reader);
+ void writeBookDialog(User& writer);
+
+ void rateBookDialog(const User& rater);
+ void commentOnBookDialog(const User& commenter);
+
+ void displayCommentsDialog() const;
+ void displayRatesDialog() const;
+
+ // TODO: Change book (add or remove page etc.)
+
+ // Functions used by main dialog
+ void displayLoginDialog();
+ void displaySignupDialog();
+ void displayUserDialog(User& currentUser);
+
+ void saveFileDialog() const;
+ void readFileDialog();
+
+ void viewBooks() const;
+ void showHelpDialog() const;
+
+ // read && write
+ void saveToFile(const char* filePath) const;
+ void readFromFile(const char* filePath);
+public:
+ // The only function used by our Kindle class
+ void display();
+};
+
diff --git a/Utills/Kindle/Page.cpp b/Utills/Kindle/Page.cpp new file mode 100644 index 0000000..a905f25 --- /dev/null +++ b/Utills/Kindle/Page.cpp @@ -0,0 +1,37 @@ +#include "Page.h"
+
+void Page::write(unsigned linesCount) {
+ if (linesCount > MAX_LINES_IN_PAGE)
+ linesCount = MAX_LINES_IN_PAGE;
+
+
+ for (size_t i = 0; i < linesCount; i++) {
+ std::cout << i + 1 << " ";
+ lines.pushBack(string());
+
+ lines[i].getLine(std::cin);
+ }
+}
+
+void Page::displayPage() const {
+ for (size_t i = 0; i < lines.getSize(); i++)
+ std::cout << lines[i] << std::endl;
+}
+
+void Page::writeToFile(std::ofstream& outFile) const {
+ int len = lines.getSize();
+ outFile.write((const char*)&len, sizeof(len));
+
+ for (size_t i = 0; i < len; i++)
+ writeString(outFile, lines[i]);
+}
+
+void Page::readFromFile(std::ifstream& inFile) {
+ int len = 0;
+ inFile.read((char*)&len, sizeof(len));
+
+ for (size_t i = 0; i < len; i++) {
+ string s = readString(inFile);
+ lines.pushBack(std::move(s));
+ }
+}
diff --git a/Utills/Kindle/Page.h b/Utills/Kindle/Page.h new file mode 100644 index 0000000..e208691 --- /dev/null +++ b/Utills/Kindle/Page.h @@ -0,0 +1,21 @@ +#pragma once
+#include"vector.hpp"
+#include"string.h"
+#include<iostream>
+#include"serialize.h"
+
+const short MAX_LINES_IN_PAGE = 26;
+
+class Page {
+private:
+ Vector<string> lines;
+
+ void write(unsigned linesCount);
+ void displayPage() const;
+
+ void writeToFile(std::ofstream& outFile) const;
+ void readFromFile(std::ifstream& inFile);
+
+ friend class Book;
+};
+
diff --git a/Utills/Kindle/Pair.hpp b/Utills/Kindle/Pair.hpp new file mode 100644 index 0000000..52859fe --- /dev/null +++ b/Utills/Kindle/Pair.hpp @@ -0,0 +1,29 @@ +#pragma once
+
+template<class T, class U>
+class Pair {
+ T first;
+ U second;
+public:
+ Pair() {
+ first = T();
+ second = U();
+ }
+ Pair(const T& fst, const U& snd) : first(fst), second(snd) {}
+
+ const T& getFirst() const {
+ return first;
+ }
+
+ const U& getSecond() const {
+ return second;
+ }
+
+ void setFirst(const T& arg) {
+ first = arg;
+ }
+
+ void setSecond(const U& arg) {
+ second = arg;
+ }
+};
\ No newline at end of file diff --git a/Utills/Kindle/Source.cpp b/Utills/Kindle/Source.cpp new file mode 100644 index 0000000..674cca7 --- /dev/null +++ b/Utills/Kindle/Source.cpp @@ -0,0 +1,6 @@ +#include"Kindle.h"
+
+int main() {
+ Kindle env;
+ env.display();
+}
\ No newline at end of file diff --git a/Utills/Kindle/User.cpp b/Utills/Kindle/User.cpp new file mode 100644 index 0000000..df1cea5 --- /dev/null +++ b/Utills/Kindle/User.cpp @@ -0,0 +1,22 @@ +#include "User.h"
+
+User::User(const string& pName, const string& pPassword) {
+ name = pName;
+ password = pPassword;
+}
+
+void User::writeToFile(std::ofstream& outFile) const {
+ writeString(outFile, name);
+ writeString(outFile, password);
+
+ writeVector(outFile, indexesOfBooksRead);
+ writeVector(outFile, indexesOfBooksWritten);
+}
+
+void User::readFromFile(std::ifstream& inFile) {
+ name = readString(inFile);
+ password = readString(inFile);
+
+ indexesOfBooksRead = readVector(inFile);
+ indexesOfBooksWritten = readVector(inFile);
+}
diff --git a/Utills/Kindle/User.h b/Utills/Kindle/User.h new file mode 100644 index 0000000..f7c2dba --- /dev/null +++ b/Utills/Kindle/User.h @@ -0,0 +1,22 @@ +#pragma once
+#include"string.h"
+#include"vector.hpp"
+#include"Book.h"
+#include"serialize.h"
+
+class User {
+private:
+ string name;
+ string password;
+ Vector<size_t> indexesOfBooksRead;
+ Vector<size_t> indexesOfBooksWritten;
+
+ friend class Kindle;
+public:
+ User() {}
+ User(const string& pName, const string& pPassword);
+
+ void writeToFile(std::ofstream& outFile) const;
+ void readFromFile(std::ifstream& inFile);
+};
+
diff --git a/Utills/Kindle/readme.md b/Utills/Kindle/readme.md new file mode 100644 index 0000000..d31119a --- /dev/null +++ b/Utills/Kindle/readme.md @@ -0,0 +1,66 @@ +# Kindle
+
+## Помощни средства които използвахме
+За решението на тази задача използваме клас string, клас vector и клас pair. String е взет директно от семинарите на първа група, с добавена функция getLine(), която използваме подобно на std::getline();
+Вектора е взет от семинарите на втора група.
+Класът Pair е единствено с цел улеснение. Той представлява наредена двойка от два темплейтни типа.
+Всяко едно нещо което сме направили с тези помощни средства може да се направи и без тях - просто кодът става по - дълъг.
+
+## Използване на командите
+### Команди, които поддържаме преди да се логне потребител:
+* login - влизаме в системата
+* signup - регистрираме се в системата
+* view - преглеждаме какви книги имаме
+* save - запазваме текущия Kindle във файл
+* load - зареждаме Kindle от файл
+* exit - излизаме от системата
+### Команди, които има потребител:
+* read - прочита книга
+* write - пише книга
+* rate - оценява книга
+* comment - коментира под книга
+* rates - проверява рейтинга на книгата
+* comments - проверява коментарите под книгата
+* view - преглежда какви книги има
+* exit - излиза от профила си
+### Команди които имаме докато четем книга:
+* n - следваща страница
+* p - предишна страница
+* @ + [number] - отива на страница, която е подадена
+* h - показва/скрива help меню
+* q - излиза от режим на четене
+
+Въвеждаме команда и натискаме Enter. След това програмата ни пита ако има нужда от допълнителна информация. Пример
+```
+> login
+> Enter user name: [Name]
+> Enter user password: [Password]
+> Success!
+>
+```
+
+## Накратко за запазването във файлове
+Имаме да запазваме сложна структура във файл. Това което можем да направим е да я разбием на по - прости. В Kindle имаме два вектора, които представляват книгите и потребителите. Ако измислим метод да запазим книга и потребител другото е лесно. Можете да видите, че в класовете представляващи книга и потребител имаме отделни функции, които се грижат за работата със запазването.
+Логиката за тях е аналогична - разбиваме структурата на по - малки структурки, които стават все по - лесни и по - лесни за запазване.
+
+## Допълнителни бележки
+В решението сме използвали friend класове. Това не винаги е лоша идея, но внимавайте с тях - възможно е да доведат до логически грешки, тоест на един клас да се дадат твърде много права над друг.
+
+При запазването на класа ще видите следния код
+```cpp
+outFile.write("#Ty", 4);
+```
+При четенето на класа ще видите следния код
+```cpp
+char typeChecker[4];
+inFile.read(typeChecker, 4);
+if (strcmp(typeChecker, "#Ty") != 0) {
+ std::cout << "Invalid file type" << std::endl;
+ return;
+}
+```
+Реално, няма как да гарантираме, че подадения файл ни е коректен. Потребителя винаги може да подаде некоректен файл, което може да счупи нашата система. За това правим следното: в началото на файла, който запазваме, записваме някаква последователност от n символа. Когато четем, прочитаме първите n (в случая 4) байта от файла и казваме - ако това е "тайният" низ, то значи този файл е писан от системата, тоест се очаква да е коректен. В противен случай приключваме изпълнението и не четем излишни данни, които могат да счупят системата ни.
+
+Също така, функционалността за промяна на книга оставяме на Вас. Чувствайте се свободни да експериментирате и pull-request вате.
+
+<b>При каквито и да е въпроси екипът по ООП е на линия.</b>
\ No newline at end of file diff --git a/Utills/Kindle/serialize.cpp b/Utills/Kindle/serialize.cpp new file mode 100644 index 0000000..af1e001 --- /dev/null +++ b/Utills/Kindle/serialize.cpp @@ -0,0 +1,71 @@ +#include"serialize.h"
+
+void writeString(std::ofstream& outFile, const string& str) {
+ int len = str.getSize();
+ outFile.write((const char*)&len, sizeof(int));
+
+ outFile.write(str.c_str(), sizeof(char) * len);
+}
+
+string readString(std::ifstream& inFile) {
+ int len = 0;
+ inFile.read((char*)&len, sizeof(len));
+
+ char* buff = new char[len + 1];
+ inFile.read(buff, sizeof(char) * len);
+
+ buff[len] = '\0';
+
+ string toReturn(buff);
+
+ delete[] buff;
+
+ return toReturn;
+}
+
+void writeVector(std::ofstream& outFile, const Vector<size_t>& v) {
+ int len = v.getSize();
+ outFile.write((const char*)&len, sizeof(int));
+
+ for (size_t i = 0; i < v.getSize(); i++)
+ outFile.write((const char*)&v[i], sizeof(size_t));
+}
+
+Vector<size_t> readVector(std::ifstream& inFile) {
+ int len = 0;
+ inFile.read((char*)&len, sizeof(int));
+ Vector<size_t> toReturn;
+ size_t read = 0;
+
+ for (size_t i = 0; i < len; i++) {
+ inFile.read((char*)&read, sizeof(size_t));
+ toReturn.pushBack(read);
+ }
+
+ return toReturn;
+}
+
+void writeCommentsToFile(std::ofstream& outFile, const Pair<string, string>& p) {
+ writeString(outFile, p.getFirst());
+ writeString(outFile, p.getSecond());
+}
+
+Pair<string, string> readCommentsFromFile(std::ifstream& inFile) {
+ string fst = readString(inFile);
+ string snd = readString(inFile);
+
+ return { fst, snd };
+}
+
+void writeRatesToFile(std::ofstream& outFile, const Pair<string, unsigned>& comments) {
+ writeString(outFile, comments.getFirst());
+ outFile.write((const char*)&comments.getSecond(), sizeof(comments.getSecond()));
+}
+
+Pair<string, unsigned> readRatesFromFile(std::ifstream& inFile) {
+ string fst = readString(inFile);
+ unsigned rate = 0;
+ inFile.read((char*)&rate, sizeof(rate));
+
+ return { fst, rate };
+}
\ No newline at end of file diff --git a/Utills/Kindle/serialize.h b/Utills/Kindle/serialize.h new file mode 100644 index 0000000..02ebc3a --- /dev/null +++ b/Utills/Kindle/serialize.h @@ -0,0 +1,20 @@ +#pragma once
+#include"string.h"
+#include"vector.hpp"
+#include"Pair.hpp"
+#include<fstream>
+
+void writeString(std::ofstream& outFile, const string& str);
+
+string readString(std::ifstream& inFile);
+
+void writeVector(std::ofstream& outFile, const Vector<size_t>& v);
+
+Vector<size_t> readVector(std::ifstream& inFile);
+void writeCommentsToFile(std::ofstream& outFile, const Pair<string, string>& p);
+
+Pair<string, string> readCommentsFromFile(std::ifstream& inFile);
+
+void writeRatesToFile(std::ofstream& outFile, const Pair<string, unsigned>& comments);
+
+Pair<string, unsigned> readRatesFromFile(std::ifstream& inFile);
\ No newline at end of file diff --git a/Utills/Kindle/string.cpp b/Utills/Kindle/string.cpp new file mode 100644 index 0000000..cb79dfb --- /dev/null +++ b/Utills/Kindle/string.cpp @@ -0,0 +1,158 @@ +#include "string.h"
+#include <cstring>
+#include <iostream>
+
+#pragma warning(disable : 4996)
+
+void string::copyFrom(const string& other)
+{
+ str = new char[strlen(other.str) + 1];
+ strcpy(str, other.str);
+ size = other.size;
+}
+void string::free()
+{
+ delete[] str;
+}
+
+string::string()
+{
+ str = new char[1];
+ str[0] = '\0';
+ size = 0;
+}
+
+string::string(const char* data)
+{
+ if (data == nullptr)
+ {
+ str = new char[1];
+ str[0] = '\0';
+ size = 0;
+ }
+ else
+ {
+ size = strlen(data);
+ str = new char[size + 1];
+ strcpy(str, data);
+ }
+}
+
+string::string(const string& other)
+{
+ copyFrom(other);
+}
+string& string::operator=(const string& other)
+{
+ if (this != &other)
+ {
+ free();
+ copyFrom(other);
+ }
+ return *this;
+}
+string::~string()
+{
+ free();
+}
+
+
+size_t string::getSize() const
+{
+ return size;
+}
+void string::concat(const string& other)
+{
+ char* temp = new char[getSize() + other.getSize() + 1];
+ strcpy(temp, str);
+ strcat(temp, other.str);
+
+ delete[] str;
+ str = temp;
+ size = size + other.getSize();
+}
+
+const char* string::c_str() const
+{
+ return str;
+}
+
+string& string::operator+=(const string& other)
+{
+ concat(other);
+ return *this;
+}
+
+void string::getLine(std::istream& outFile)
+{
+ delete[] str;
+ char buff[1024];
+
+ outFile.getline(buff, 1024, '\n');
+ size_t len = strlen(buff);
+ str = new char[len + 1];
+ for (size_t i = 0; i < len; i++)
+ str[i] = buff[i];
+ str[len] = '\0';
+ size = len;
+}
+
+string operator+(const string& lhs, const string& rhs)
+{
+ string copyOfLeft(lhs);
+ copyOfLeft += rhs;
+ return copyOfLeft;
+}
+
+std::ostream& operator<<(std::ostream& stream, const string& str)
+{
+ stream << str.str;
+ return stream;
+}
+
+std::istream& operator>>(std::istream& stream, string& str)
+{
+ delete[] str.str;
+ char buff[1024];
+ stream >> buff;
+
+ str.size = strlen(buff);
+ str.str = new char[str.size + 1];
+ strcpy(str.str, buff);
+
+ return stream;
+}
+
+bool operator==(const string& lhs, const string& rhs)
+{
+ return strcmp(lhs.c_str(), rhs.c_str()) == 0;
+}
+bool operator<=(const string& lhs, const string& rhs)
+{
+ return strcmp(lhs.c_str(), rhs.c_str()) <= 0;
+
+}
+bool operator<(const string& lhs, const string& rhs)
+{
+ return strcmp(lhs.c_str(), rhs.c_str()) < 0;
+
+}
+
+string::string(string&& otherString)
+{
+ str = otherString.str;
+ size = otherString.size;
+ otherString.str = nullptr;
+}
+
+string& string::operator=(string&& otherString)
+{
+ if (this != &otherString)
+ {
+ free();
+ str = otherString.str;
+ otherString.str = nullptr;
+ size = otherString.size;
+ }
+ return *this;
+}
\ No newline at end of file diff --git a/Utills/Kindle/string.h b/Utills/Kindle/string.h new file mode 100644 index 0000000..d5a06be --- /dev/null +++ b/Utills/Kindle/string.h @@ -0,0 +1,42 @@ +#pragma once
+
+#include <fstream>
+#include <iostream>
+class string
+{
+ char* str;
+ size_t size;
+
+ void copyFrom(const string& other);
+ void free();
+
+public:
+ string();
+ string(const char*);
+
+ string(const string&);
+
+ string(string&&); //move constructor that accepts rvalue;
+
+ string& operator=(const string& other);
+ string& operator=(string&& other); //move op= that accepts rvalue;
+
+ ~string();
+
+ size_t getSize() const;
+ void concat(const string& other);
+
+ const char* c_str() const;
+
+ string& operator+=(const string& other);
+
+ friend std::ostream& operator<<(std::ostream& stream, const string& str);
+ friend std::istream& operator>>(std::istream& stream, string& str);
+ void getLine(std::istream& out);
+};
+
+string operator+(const string& lhs, const string& rhs);
+
+bool operator==(const string& lhs, const string& rhs);
+bool operator<=(const string& lhs, const string& rhs);
+bool operator<(const string& lhs, const string& rhs);
\ No newline at end of file diff --git a/Utills/Kindle/vector.hpp b/Utills/Kindle/vector.hpp new file mode 100644 index 0000000..1afb2a5 --- /dev/null +++ b/Utills/Kindle/vector.hpp @@ -0,0 +1,239 @@ +#pragma once
+#include<iostream>
+const size_t DEFAULT_CAPACITY = 4;
+
+template <typename T>
+class Vector {
+private:
+ T* data;
+ size_t size;
+ size_t capacity;
+public:
+ Vector();
+ Vector(const Vector<T>&);
+ Vector(Vector<T>&&);
+ Vector<T>& operator=(const Vector<T>&);
+ Vector<T>& operator=(Vector<T>&&);
+ ~Vector();
+
+ size_t getSize() const;
+ size_t getCapacity() const;
+
+ void pushBack(const T&);
+ void pushBack(T&& n);
+ void pushAt(const T&, const size_t);
+ void pushAt(T&&, const size_t);
+ T& popBack();
+ T& popAt(const size_t);
+ T& operator[](const size_t);
+ const T& operator[](const size_t) const;
+ bool empty() const;
+ void clear();
+ void swap(const Vector<T>&);
+private:
+ void copy(const Vector&);
+ void free();
+ void move(Vector&&);
+
+ size_t calculateCapacity(const size_t) const;
+ void resize(const size_t);
+};
+
+template <typename T>
+Vector<T>::Vector() {
+ data = nullptr;
+ capacity = size = 0;
+}
+
+template <typename T>
+Vector<T>::Vector(const Vector<T>& other) {
+ copy(other);
+}
+
+template <typename T>
+Vector<T>::Vector(Vector<T>&& other) {
+ move(std::move(other));
+}
+
+template <typename T>
+Vector<T>& Vector<T>::operator=(const Vector<T>& other) {
+ if (this != &other)
+ {
+ free();
+ copy(other);
+ }
+
+ return *this;
+}
+
+template <typename T>
+Vector<T>& Vector<T>::operator=(Vector<T>&& other) {
+ if (this != &other)
+ {
+ free();
+ move(std::move(other));
+ }
+
+ return *this;
+}
+
+template <typename T>
+Vector<T>::~Vector() {
+ free();
+}
+
+template <typename T>
+size_t Vector<T>::getSize() const {
+ return size;
+}
+
+template <typename T>
+size_t Vector<T>::getCapacity() const {
+ return capacity;
+}
+
+template <typename T>
+void Vector<T>::pushBack(const T& element) {
+ if (size + 1 > capacity)
+ resize(size + 1);
+
+ data[size++] = element;
+}
+
+
+template <typename T>
+void Vector<T>::pushBack(T&& element) {
+ if (size + 1 > capacity)
+ resize(size + 1);
+
+ data[size++] = element;
+}
+
+template <typename T>
+void Vector<T>::pushAt(const T& element, const size_t index) {
+ if (size + 1 > capacity)
+ resize(size + 1);
+
+ for (size_t i = size; i > index; i--)
+ data[i] = data[i - 1];
+
+ data[index] = element;
+ size++;
+}
+
+template <typename T>
+void Vector<T>::pushAt(T&& element, const size_t index) {
+ if (size + 1 > capacity)
+ resize(size + 1);
+
+ for (size_t i = size; i > index; i--)
+ data[i] = data[i - 1];
+
+ data[index] = element;
+ size++;
+}
+
+template <typename T>
+T& Vector<T>::popBack() {
+ if (empty())
+ throw "Vector is empty";
+
+ return data[--size];
+}
+
+template <typename T>
+T& Vector<T>::popAt(size_t index) {
+ if (index < 0 || index >= size)
+ throw "Invalid index";
+
+ T temp = data[index];
+ for (size_t i = index; i < size - 1; i++)
+ data[i] = data[i + 1];
+
+ size--;
+ return temp;
+}
+
+template <typename T>
+T& Vector<T>::operator[](const size_t index) {
+ if (index < 0 || index >= size)
+ throw "Invalid index";
+
+ return data[index];
+}
+
+template <typename T>
+const T& Vector<T>::operator[](const size_t index) const {
+ if (index < 0 || index >= size)
+ throw "Invalid index";
+
+ return data[index];
+}
+
+template <typename T>
+bool Vector<T>::empty() const {
+ return size == 0;
+}
+
+template <typename T>
+void Vector<T>::clear() {
+ delete[] data;
+ capacity = DEFAULT_CAPACITY;
+ data = new T[capacity];
+ size = 0;
+}
+
+template <typename T>
+void Vector<T>::swap(const Vector<T>& other) {
+ Vector<T> tempVector(std::move(*this));
+ *this = std::move(other);
+ other = std::move(tempVector);
+}
+
+template <typename T>
+void Vector<T>::copy(const Vector<T>& other) {
+ size = other.size;
+ capacity = other.capacity;
+ data = new T[capacity];
+
+ for (size_t i = 0; i < size; i++)
+ data[i] = other[i];
+}
+
+template <typename T>
+void Vector<T>::free() {
+ delete[] data;
+ data = nullptr;
+ capacity = size = 0;
+}
+
+template <typename T>
+void Vector<T>::move(Vector&& other)
+{
+ data = other.data;
+ size = other.size;
+ capacity = other.capacity;
+
+ other.data = nullptr;
+ other.capacity = other.size = 0;
+}
+template <typename T>
+size_t Vector<T>::calculateCapacity(const size_t number) const {
+ size_t result = DEFAULT_CAPACITY;
+ while (number > result)
+ result *= 2;
+
+ return result;
+}
+
+template <typename T>
+void Vector<T>::resize(const size_t expectedCapacityToFit) {
+ capacity = calculateCapacity(expectedCapacityToFit);
+ T* temp = new T[capacity];
+
+ for (size_t i = 0; i < size; i++)
+ temp[i] = data[i];
+
+ delete[] data;
+ data = temp;
+}
\ No newline at end of file |
