I am studying reading/writing to binary files with C ++, i'm trying to apply with object lists,
class Customer {
public:
int code;
string name;
void ini(int code, string name);
}
list<Customer> *customers;
customers = new list<Customer>[2];
Customer *cl = new Customer();
cl->ini(17, "John");
customers[0].push_back(*cl);
Writing method:
ofstream wf("customers.dat", ios::out | ios::binary);
for(int i = 0; i < 2; i++) {
wf.write((char *) &customers[i], sizeof(Customer));
cout << i << endl;
}
wf.close();
And reading method:
list<Customer> *customer2;
customer2= new list<Customer>[2];
for(int i = 0; i < 2; i++) {
rf.read((char *) &customer2[i], sizeof(Customer)); //some way of using the push_back by here?
}
rf.close();
after debugging, the recording seems to go well, however when I do the reading, only the first item of the first vector is loaded, the loop cannot find an end and the program stops.
for(int i=0; i < 2; i++) {
cout << i << " ";
for (auto x : customers[i])// here fails
cout << x->name << endl; //print the first member and break
}
what is the correct way to manipulate object vector lists?
P.S: For the sizeof, i've already tried: (customers, Customer, customer[i], customer2[i])
#include<bits/stdc++.h>when you know what you are doing (and at that point you probably won't be using it). The way you're currently using it suggests you don't know how it should be used.clientes2 = new list<Customer>[2];is not alistwith two items in it. It's an array of twolists with 0 items in them. What you want to do is make alist:list<Customer> clientes2;. then make aCustomer temp;and then read intotempwithrf.read((char *) &temp, sizeof(temp));. then addtemp to theclientes2:clientes2.push_nack(ttemp);. BUT!!!!!!Customer` contains astringandstringis too complicated to read from a file withread. It's also too complicated towrite.listin C++ is almost always a doubly linked list. If you're coming in from a language wherelistis a dynamic array, you wantstd::vectorinstead.