Here is an example program that reads the 'books.txt' file and searches for books published between 1950 and 1999:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

struct Book {
    std::string title;
    std::string author;
    int year;
};

std::vector<Book> readBooksFromFile(const std::string& filename) {
    std::vector<Book> books;
    std::ifstream file(filename);

    if (!file) {
        std::cerr << "Error opening file: " << filename << std::endl;
        return books;
    }

    std::string line;
    while (std::getline(file, line)) {
        std::string title, author;
        int year;

        std::istringstream iss(line);
        if (iss >> title >> author >> year) {
            books.push_back({title, author, year});
        }
    }

    file.close();
    return books;
}

void searchBooksByYear(const std::vector<Book>& books, int startYear, int endYear) {
    for (const Book& book : books) {
        if (book.year >= startYear && book.year <= endYear) {
            std::cout << "Title: " << book.title << std::endl;
            std::cout << "Author: " << book.author << std::endl;
            std::cout << "Year: " << book.year << std::endl;
            std::cout << std::endl;
        }
    }
}

int main() {
    std::string filename = "books.txt";
    std::vector<Book> books = readBooksFromFile(filename);

    int startYear = 1950;
    int endYear = 1999;
    searchBooksByYear(books, startYear, endYear);

    return 0;
}

Make sure to create a file called 'books.txt' with test data in the format: <title> <author> <year>. Each book should be on a separate line. For example:

Book1 Author1 1985
Book2 Author2 2005
Book3 Author3 1972

This program reads the books from the file, stores them in a vector of Book structs, and then searches for books published between the specified start and end years. It prints the details of each matching book.


原文地址: https://www.cveoy.top/t/topic/o1R2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录