LB9

mail@pastecode.io avatar
unknown
c_cpp
6 months ago
2.5 kB
3
Indexable
Never
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

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

void saveBookInfo(const string& filename, const BookInfo books[], int size) {
    ofstream file(filename);

    for (int i = 0; i < size; i++) {
        file << books[i].title << ","
             << books[i].authorFirstName << ","
             << books[i].authorLastName << ","
             << books[i].publicationYear << endl;
    }

    file.close();
}

void loadBookInfo(const string& filename, BookInfo books[], int& size) {
    ifstream file(filename);
    string line;
    size = 0;

    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[size++] = book;
    }

    file.close();
}

int main() {
    string filename = "books.txt";
    const int MAX_BOOKS = 10;
    BookInfo books[MAX_BOOKS];
    int numBooks = 0;

    //Додати книги до масиву
    books[numBooks++] = {"1984", "George", "Orwell", 1949};
    books[numBooks++] = {"Brave New World", "Aldous", "Huxley", 1932};

    //Зберегти інформацію про книгу у файлі
    saveBookInfo(filename, books, numBooks);

    //Завантажити інформацію про книгу з файлу
    loadBookInfo(filename, books, numBooks);

    //Пошук книги за прізвищем автора
    string searchLastName;
    cout << "Enter the author's last name (Orwell or Huxley): ";
    cin >> searchLastName;

    bool bookFound = false;
    for (int i = 0; i < numBooks; i++) {
        if (books[i].authorLastName == searchLastName) {
            cout << "Title: " << books[i].title << endl
                      << "Author: " << books[i].authorFirstName << " " << books[i].authorLastName << endl
                      << "Publication Year: " << books[i].publicationYear << endl;
            bookFound = true;
            break;
        }
    }

    if (!bookFound) {
        cout << "No book found for the given author's last name." << endl;
    }

    return 0;
}