Why does reading a string cause errors?
-
Hi all, I have the following read/write program. typedef struct { string s1; string s2; } Names; int main { fstream fout("data.dat", ios::in | ios::out | ios::binary); Names name; name.s1.assign("abc"); name.s2.assign("xyz"); fout.write((char*)name, sizeof(Names)); fout.close } And then, I create another program to read this file int main { fstream fin("data.dat", ios::in | ios::binary); Names *name = new Names(); fin.read((char*)name, sizeof(Names)); // --> Till here, it's Ok. But if I want to access the struct. For example: cout << name->s1.c_str() << endl; fout.close } The strange thing is that, if I combine write and read file in one program, then no problem. But if I creat2 2 differenct programs, there's problems. Can anyone help me out? THank you in advance
-
Hi all, I have the following read/write program. typedef struct { string s1; string s2; } Names; int main { fstream fout("data.dat", ios::in | ios::out | ios::binary); Names name; name.s1.assign("abc"); name.s2.assign("xyz"); fout.write((char*)name, sizeof(Names)); fout.close } And then, I create another program to read this file int main { fstream fin("data.dat", ios::in | ios::binary); Names *name = new Names(); fin.read((char*)name, sizeof(Names)); // --> Till here, it's Ok. But if I want to access the struct. For example: cout << name->s1.c_str() << endl; fout.close } The strange thing is that, if I combine write and read file in one program, then no problem. But if I creat2 2 differenct programs, there's problems. Can anyone help me out? THank you in advance
int main { fstream fout("data.dat", ios::in | ios::out | ios::binary); Names name; <--- not a pointer name.s1.assign("abc"); name.s2.assign("xyz"); fout.write((char*)name, sizeof(Names)); <--- never thought you can cast fout.close a structure to a pointer to } char. Either this works for weird reasons, or you made a mistake copying (char *)&name.