I need some help with a program, here is the function that i'm stuck on:
"void write_books(string book_file_name, vector<book> &my_books);
This function will write the values from the vector my_books to a file with the name book_file_name. The string book_file_name should be the same as your input file for books (books.txt). If you write the values from the vector my_books to the input file, you will ensure that any changes made to the vector while the program is running will be reflected in the next run of the program."
So basically, I read six lines (name, price, stock, publisher, author, and isbn) from a file for a book object that needs to be stored into a vector. Once I read these six lines out, I create a book pointer, point to the six setter functions for these elements, and then push them into a vector. And it needs to be able to do it for an nth amount of books. Here is an example of the code:
Code:
void read_books(string book_file_name, vector<book> &my_books)
{
string name, price, stock, publisher, author, isbn;
book *bookpt;
ifstream fin;
string bookFile = "books.txt";
fin.open(bookFile);
while(fin >> name >> price >> stock >> publisher >> author >> isbn)
{
bookpt = new book;
bookpt -> setName(name);
bookpt -> setPrice(price);
bookpt -> setStock(stock);
bookpt -> setPublisher(publisher);
bookpt -> setAuthor(author);
bookpt -> setIsbn(isbn);
my_books.push_back(*bookpt);
}
fin.close();
}
The end result is my_books[0] containing this when outputted to the screen using a print_info function (which is a parent class function):
Code:
Code:
for(int i = 0; i < all_books.size(); i++)
{
my_books[i].print_info();
}
Output:
Product Name: Book
Product Price: Price
Number in Stock: Stock
Publisher: Publisher
Author: Author
ISBN: ISBN
Now, onto the original question. I can read elements from a file, store them into a vector, and output them onto the screen. The thing i'm having problems with is outputting them into a new final file. Here is what I have so far for the function:
Code:
void write_books(string book_file_name, vector<book> &my_books)
{
ofstream fout;
book_file_name = "final_books.txt";
fout.open(book_file_name);
for(int i = 0; i < my_books.size(); i++)
{
fout << my_books[i] << endl;
}
fout.close();
}
I'm having problems with this bit of code right here:
Code:
fout << my_books[i] << endl;
It won't let me output it like this for some reason. I've tried using iterators as well, nothing has worked so far.