How to record immediately the entire structure (that contains string) to a binary file?

An example of the structure
struct anketa
 int year;
 string fio;

Had to record this method, then to run separately another function that can read the file, but before that, not to add records to a file(well, that is purely reading)
Tried so: after the user enters a string calculate string.size() + 1 and add on the sizeof(int), but after reading from a file gives some nonsense
March 23rd 20 at 19:42
2 answers
March 23rd 20 at 19:44
#include <iostream>
#include <fstream> // std::fstream

using namespace std;

typedef struct
 int year;
 string fio;
} Anketa;

int main () 
 Anketa anketa;
 anketa.year = 1643;
 anketa.fio = "Isaac Newton John";

 // *** Writing ***
 fstream fs; ("anketa.dat", std::fstream::out | std::fstream::binary);

 fs.write((char*) &anketa.year, sizeof(int));
 size_t len = anketa.fio.length();
 fs.write((char*) &len, sizeof(size_t));
 fs.write(, len);


 // *** Reading *** ("anketa.dat", std::fstream::in | std::fstream::binary);*) &anketa.year, sizeof(int));*) &len, sizeof(size_t));
 char buf[len+1];, len);
 buf[len] = 0;
 anketa.fio = buf;


 cout << anketa.year << "" << anketa.fio << endl;

 return 0;
The point is that the entry, respectively, and then and reading from a binary file should occur in one line, if for example all elements of a structure was simple - eleanora.Cruickshank25 commented on March 23rd 20 at 19:47
March 23rd 20 at 19:46
Well, for POD has something like this to work:
anketa a;

std::ofstream out(file_name);
out.write(reinterpret_cast<char*>(&a), sizeof(a));

// ...

std::ifstream in(file_name);<char*>(&a), sizeof(a));

But there you have std::string is, and it is necessary to char* convert to a record. It's more than one line. Therefore, such read/write have to make a separate function.

Find more questions by tags C++