Converting a custom type

Hi everyone, I have some problems in converting a custom type to the type in binary file.

Here is the code.

1
2
3
4
5
6
7
8
9
10
11
void CreateAccount()
{
	Account account;
	ofstream out_file;
	out_file.open("account.dat", std::ios_base::binary);
	if (out_file.is_open())
	{
		out_file.write(account,1024);// here is the problem!
	}
	out_file.close();
}


This is where I input the info of an account
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void Account::CreateAccount()
{
	cout << "Nhap so tai khoan: ";
	cin >> account_number_;
	cin.ignore();
	cout << "Nhap ten chu tai khoan: ";
	cin.getline(name_,100);
	cout << "Nhap loai tai khoan: ";
	cin >> type_;
	while (type_ != 'N' || type_ != 'V')
	{
		cout << "Vui long nhap lai loai tai khoan: ";
		cin >> type_;
	}
	cout << "So du ban dau: ";
	cin >> balance_;
}


Here is the class of it.
1
2
3
4
5
6
7
class Account
{
private:
	int account_number_; // userID
	char name_[100]; // userName
	int balance_; // balance
	char type_; // type of account. N: normal. V: VIP 


What steps should I do convert it? Any suggestion?
Last edited on
 
out_file.write(account,1024);// here is the problem! 


https://en.cppreference.com/w/cpp/io/basic_ostream/write

The first parameter is expecting NOT a custom data type. It should be a string. To write them to the file, you will need to convert each member of the class into a string, and then you can use the write(const char*, std::streamsize n) function to put it into a file.
Last edited on
You should read this.
https://isocpp.org/wiki/faq/serialization

> out_file.write(account,1024);// here is the problem!
For writing binary data, you would write
 
out_file.write(reinterpret_cast<char*>(&account),sizeof(account));


But that only works if your class contains only POD (Plain-Old-Data) types.
https://stackoverflow.com/questions/146452/what-are-pod-types-in-c
Note that this link suggests that private members can't be POD.
> Note that this link suggests that private members can't be POD.
that classes with private members are not POD
Registered users can post here. Sign in or register to post.