Strangest Error yet!!

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
bugzpodder
Experienced poster
Posts: 147
Joined: Fri Jun 13, 2003 10:46 pm

Strangest Error yet!!

Post by bugzpodder »

Code: Select all

for (int i=0;i<1;i++){
	Client s(44,"Mike","Brown","333333");
	ofstream fout("test.bin",ios::binary);
	fout.write((char *) (&s),sizeof(Client));
	fout.flush();
	fout.close();
	}
	Client s2;
	ifstream fin("test.bin",ios::binary);
	fin.read((char *) (&s2),sizeof(Client));
	cout<<s2.display()<<endl;
	fin.close();

Code: Select all


	Client s(44,"Mike","Brown","333333");
	ofstream fout("test.bin",ios::binary);
	fout.write((char *) (&s),sizeof(Client));
	fout.flush();
	fout.close();

	Client s2;
	ifstream fin("test.bin",ios::binary);
	fin.read((char *) (&s2),sizeof(Client));
	cout<<s2.display()<<endl;
	fin.close();
the first piece of code crashes
after deleting the for loop, the second piece of code runs with no problems. it must be some error caused by the local variable Client s (if you delcare it outside the for loop it works fine)
why is it happening??
and suppose i want to delcare it inside the for loop, how do i fix it??

bugzpodder
Experienced poster
Posts: 147
Joined: Fri Jun 13, 2003 10:46 pm

Post by bugzpodder »

ok I know why it crashes now. i used strings in the clients and it only dumps the pointer to the string (C++ basic_string) to the file. hence if we declare the class inside the for loop and exits, only the pointer is saved, and that explains why all the numbers are correct and the strings are incorrect

so is there a way to dump basic_string in the file?

Post Reply

Return to “C++”