/** * Clayton Cafiero * CS 2240 * 2021-Jan-17 */ #ifndef BOOK_H #define BOOK_H #include #include #include #include #include /* * Book class */ class Book { private: std::string title; std::string author; std::string publisher; int year; public: Book() { this->title = ""; this->author = ""; this->publisher = ""; this->year = 0; } // Constructor Book(std::string title, std::string author, std::string publisher, int year) { this->title = title; this->author = author; this->publisher = publisher; this->year = year; } // Getters // use const to specify that the method won't modify the object std::string getTitle() const { return title; } std::string getAuthor() const { return author; } std::string getPublisher() const { return publisher; } int getYear() const { return year; } // Setters void setTitle(std::string title) { this->title = title; } void setAuthor(std::string author) { this->author = author; } void setPublisher(std::string publisher) { this->publisher = publisher; } void setYear(int year) { this->year = year; } // Overloaded Operators friend std::ostream& operator << (std::ostream& outs, const Book& book) { outs << std::left << std::setw(30) << book.title; outs << std::left << std::setw(25) << book.author; outs << std::left << std::setw(20) << book.publisher; outs << std::left << std::setw(6) << book.year; return outs; } friend bool operator == (const Book &lhs, const Book &rhs) { // Use the unique field to determine if the two objects are equal return lhs.title == rhs.title; } }; // A global function is declared outside the scope of the class // An ampersand & means that the vector is being passed by reference bool readBooksFromFile(std::string filename, std::vector& books) { // Read books in from file std::ifstream fIn; fIn.open("../" + filename); std::string header = ""; if (!fIn) { // Bad file / could not open return false; } // While the file stream is in a good state and // we are not at the end of file (EOF) while (fIn && fIn.peek() != EOF) { std::string title, author, publisher, callNumber; int year; char comma = ','; // Read in the name // Use getline with three arguments to specify stop character getline(fIn, title, ','); getline(fIn, author, ','); fIn >> year; fIn >> comma; getline(fIn, publisher); // Create a Book object and add it to the vector books.push_back(Book(title, author, publisher, year)); } fIn.close(); return true; } #endif // BOOK_H