Click here to Skip to main content
15,891,785 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include<iostream>
#include<fstream>
#include<vector>

class Book
{
public:
	Book();
	Book(std::string set_book_name, std::string set_ISBN, bool set_check);
	Book(const char* set_book_name, const char* set_ISBN, bool set_check);
	Book(const Book& one);
private:
	std::string book_name;
	std::string ISBN;
	bool check;
};

class User
{
public:
	User();
private:
	void read_in_data(void);
	std::vector<Book> list;
};

Book::Book() :book_name(""), ISBN(""), check(true)
{

}

Book::Book(const char* set_book_name, const char* set_ISBN, bool set_check) : book_name(set_book_name), ISBN(set_ISBN), check(set_check)
{

}

Book::Book(const Book& one)
{
	book_name = one.book_name;
	ISBN = one.ISBN;
	check = one.check;
}


User::User()
{
	read_in_data();
}

void User::read_in_data(void)
{
	std::ifstream ins;
	ins.open("data.dat");
	if (ins.fail())
	{
		std::cout << "File data.dat can't be read.\n";
		exit(1);
	}
	Book temp;
/*	while (!ins.eof())                          
	{
		ins.read(reinterpret_cast<char *>(&temp), sizeof(Book));
		list.push_back(temp);
	}*/
	while (ins.read(reinterpret_cast<char *>(&temp), sizeof(Book)))
	{
		list.push_back(temp);
	}
	ins.close();
	return;         //********PROBLEM HERE.
}

int main()
{
/*	std::vector<Book> book;        //LINE:75
	std::ofstream outs;
	outs.open("data.dat");
	if (outs.fail())
	{
		std::cout << "File can't be written.\n";
		exit(1);
	}
	book.push_back(Book("asd", "123", false));
	book.push_back(Book("asd", "1234", false));
	book.push_back(Book("asd", "finally", false));
	std::vector<Book>::iterator p = book.begin();
	while (p!=book.end())
		outs.write(reinterpret_cast<char*>(&(*p++)), sizeof(Book));
	outs.close();*/           //LINE:89
	User user;					//LINE::90
	return 0;
}


What I have tried:

My programming steps is:
First:I note line::90,then execute this program to write data to file data.dat.

Second:I note line::75 to line::89,then execute program to read data from data.dat to object User::user,at this time,memory error was given.


By the way,My English grammer is bad,I hope you can try to understand my intention,I really need your help.
Posted
Updated 1-Jun-16 10:43am
v4

1 solution

You cannot serialize/deserialize a class containing <code>std::string that way. See, for instance c++ - Serializing a class which contains a std::string - Stack Overflow[^].
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 1-Jun-16 19:50pm    
5ed.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900