#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>
using namespace std;
//create a class for one book
class Book
{
//member variables
public:
string title;
string author;
int year;
//function to print the book details
void print() const
{
cout << "Title: " << title << endl;
cout << "Authot: " << author << endl;
cout << "Year: " << year << endl;
}
};
int main()
{
std::string filename;
//prompt the user to enter the file name
/*
cout << "Enter filename: ";
cin >> filename;
*/
filename = "books.txt";
//open the file
fstream file;
file.open(filename.c_str());
int nx;
//read the first line of the file to know the number of books
file >> nx;
//move to the next line of the file
file.ignore(numeric_limits<streamsize>::max(), '\n');
//allocate an array of n Book
vector<Book> books(nx);
//read the data for n books from the file
for (int i = 0; i < nx; i++)
{
//read file and initialize the books array
getline(file, books[i].title);
getline(file, books[i].author);
file >> books[i].year;
//move to the next line of the file
file.ignore(numeric_limits<streamsize>::max(), '\n');
}
//Display the output
cout << "Books found: " << nx << endl;
for (int i = 0; i < nx; i++)
{
cout << "\nBook " << i + 1 << ":" << endl;
books[i].print();
}
return 0;
}
3
Book 1
Author 1
2021
Book 2
Author 2
2021
Book 3
Author 3
2021