Answer the question
In order to leave comments, you need to log in
How to save / load data from a binary file through classes?
There is a class Students.
class Students{
public:
void save();
void load();
~Students();
//Конструктор класса Students
Students(string firstname, string lastname);
//Установка имени
void set_firstname(string);
//Получение имени
string get_firstname();
//Установка фамилии
void set_lastname(string);
//Получение фамилии
string get_lastname();
private:
//Имя
string firstname;
//Фамилия
string lastname;
};
Students::Students(string firstname, string lastname)
{
Students::set_firstname(firstname);
Students::set_lastname(lastname);
}
void Students::save() {
ofstream fout("Students.dat", ios::binary | ios::out);
string firstname = Students::get_firstname();
string lastname = Students::get_lastname();
fout.write((char*)&lastname, sizeof(firstname));
fout.write((char*)&lastname, sizeof(lastname));
fout << std::endl;
fout.close();
}
Answer the question
In order to leave comments, you need to log in
> fout.write((char*)&lastname, sizeof(firstname));
You write the internal contents of the class to the file. You can not do it this way. If you need to write a line, write like this:
But then you will need to read it. And for this you need to know its size, so you need to do this:
size_t size = firstname.size();
fout.write(reinterpret_cast<const char *>(&size), sizeof(size));
fout.write(lastname.data(), size);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question