Add the following struct named Book to your code struct Book { string title; str
ID: 3544630 • Letter: A
Question
Add the following struct named Book to your code
struct Book {
string title;
string author;
double price;
};
Overload the << operator for the Book struct. Output the data in the form: author wrote title. For example, if the author is Mark Twain, and the title is Tom Sawyer, using the << operator would result in Mark Twain wrote Tom Sawyer.
Open the file bookDatabase.db for reading. The format of the file is:
The column for author names is 20 characters wide.
The column for book titles is 30 characters wide.
The maximum price for a book is 99.99. Prices always include a decimal point and cents. There is no dollar sign.
All columns are the same width for every book. If the value is shorter than the width, then the data is padded with spaces.
There is exactly one space between an author and a title.
There is exactly one space between the title and the price.
The file is in Windows format.
One book (author, title, price) per line.
Create a variable in your code like this:
Book myBook;
Read every line in the bookDatabase.db file into the myBook variable and then print it using your overloaded << operator.
Explanation / Answer
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
struct Book
{
string title;
string author;
double price;
};
ostream& operator<<(ostream &out, Book &cBook)
{
out << cBook.author <<" wrote "<< cBook.title << endl;
return out;
}
int main()
{
Book myBook;
ifstream infile("bookDatabase.db");
if(!infile)
{
cout <<"Unable to open file bookDatabase.db. so exiting from program" << endl;
return 0;
}
while(!infile.eof())
{
infile >> myBook.author >> myBook.title >> myBook.price;
cout << myBook;
}//end while
infile.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.