Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.3 kB
3
Indexable
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
using namespace std;

struct BookInfo {
    string title;
    string authorFirstName;
    string authorLastName;
    int publicationYear;
};

void saveBookInfo(const string& filename, const map<string, BookInfo>& books) {
    ofstream file(filename);

    for (const auto& book : books) {
        file << book.second.title << ","
             << book.second.authorFirstName << ","
             << book.second.authorLastName << ","
             << book.second.publicationYear << endl;
    }

    file.close();
}

map<string, BookInfo> loadBookInfo(const string& filename) {
    map<string, BookInfo> books;
    ifstream file(filename);
    string line;

    while (getline(file, line)) {
        BookInfo book;
        stringstream ss(line);
        string field;

        getline(ss, book.title, ',');
        getline(ss, book.authorFirstName, ',');
        getline(ss, book.authorLastName, ',');
        getline(ss, field, ',');
        book.publicationYear = stoi(field);

        books[book.authorLastName] = book;
    }

    file.close();
    return books;
}

int main() {
    string filename = "books.txt";
    map<string, BookInfo> books;

    // Add books to the map
    books["Orwell"] = {"1984", "George", "Orwell", 1949};
    books["Huxley"] = {"Brave New World", "Aldous", "Huxley", 1932};

    // Save book information to a file
    saveBookInfo(filename, books);

    // Load book information from a file
    map<string, BookInfo> loadedBooks = loadBookInfo(filename);

    // Search for a book by the author's last name
    string searchLastName;
    cout << "Enter the author's last name (Orwell or Huxley)";
    cin >> searchLastName;

    auto it = loadedBooks.find(searchLastName);
    if (it != loadedBooks.end()) {
        cout << "Title: " << it->second.title << endl
                  << "Author: " << it->second.authorFirstName << " " << it->second.authorLastName << endl
                  << "Publication Year: " << it->second.publicationYear << endl;
    } else {
        cout << "No book found for the given author's last name." << endl;
    }

    return 0;
}