menu

arrow_back How to correct the output vector of the structure in the file?

by
1 vote
Good day!
The file appears to do the same is introduced +what is the symbol?
+not yet clear how prailno I did it all.
If anyone can suggest to help,thanks in advance.
I will be glad to any comment..
#include "books.h"
#include "global.h"
#include "menu.h"
#include "readers.h"
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>

vector<structBook> vecStructBook;
int bookCount=0;
structBook book;
vector<structBook>::iterator iterBook;

void addBook(void)
{
ofstream bookDatabase;
bookDatabase.open("bookDatabaseFile.txt", ios::app);
if (!bookDatabase)
cout << "File open error" << endl;
else
{
cout << "Please enter information about book" << endl;
cout << "How much book you want to enter" << endl;
int bookNumberForEnter;
cin >> bookNumberForEnter;
for (int i=0; i< bookNumberForEnter;i++)
{
cout << "Book id: " << endl;
cin >> book.bookId;
cout << "Please enter book name: ";
cin >> book.bookName;
cout << "Please enter book author name: ";
cin >> book.bookAuthorName;
cout << "Please enter book author surname: ";
cin >> book.bookAuthorSurname;
cout << "Please enter publising house name: ";
cin >> book.publishingHouse;
cout << "Please enter book publishing year: ";
cin >> book.year;
cout << "Please enter book pages amount:";
cin >> book.pages;
cout << "Please enter is book on place:";
cin >> book.onplace;
cout << "Please enter book genre:";
cin >> book.genre;
cout << "Please enter book section:";
cin >> book.section;
bookCount++;
vecStructBook.push_back(book);
for (iterBook = vecStructBook.begin(); iterBook < vecStructBook.end(); iterBook++)
{
bookDatabase.write(reinterpret_cast<char*>(&book), sizeof(structBook));
cout << "Book added" << endl;
}
}
bookDatabase.close();
}
}

1 comment

And what "Standard streams"? cin, coutthe code contains, but the question is not about them.

1 Answer

by
 
Best answer
0 votes
void writeBinary(ostream& os, structBook const& book)
{
ostringstream ss;
ss << book.bookId
<< book.bookName.size() << book.bookName
<< book.bookAuthorName.size() << book.bookAuthorName
<< book.bookAuthorSurname.size() << book.bookAuthorSurname
<< book.year << book.pages << book.onplace
<< book.genre.size() << book.genre
<< book.section.size() << book.section;
os.write(reinterpret_cast<char*>(ss.str().size()), sizeof(decltype(ss.str().size())));
os.write(ss.str().data(), ss.str().size());
}

// ...

for(auto const& b : vecStructBook)
{
writeBinary(bookDatabase, b);
}

считывать наоборот.