0

Hi!
Using string, ifstream and ofstream object. Compiling - ok, but give a run-time error after printing Name in ReadData() function.
My Person class include only one string member "name" and function "Name()" which return string object "this->name". And constructor with string parameter of course...

#include <iostream>
#include <fstream>
#include "Person.h"
using namespace std;

void ReadData(string path)
{
	ifstream rFile;
	Person temp;
	rFile.open(path, ios::in);
	rFile.read((char*)&temp, sizeof(temp));
	cout << temp.Name();
	rFile.close();
}

void WriteData(string path)
{
	ofstream wFile(path, ios::out);
	Person man("My Name");
	cout << man.Name();
	wFile.write((char*)&man, sizeof(man));	
	wFile.close();
}

can someone give a tips for this?
Thanks

2
Contributors
1
Reply
3
Views
6 Years
Discussion Span
Last Post by Narue
0

Just because you can cast an object to a pointer to char doesn't mean it's safe. Unless your class is POD, punning to a byte stream is begging for data corruption.

Edited by Narue: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.