Hi, I recently started learning C++ because i wan to develop games, anyway i just got to file i/o part and i got a problem with the binary file read.
I created a class to test the binary file i/o:
#ifndef KAIZOKU_H
#define KAIZOKU_H
#include <string>
#include <fstream>
class Kaizoku
{
public:
Kaizoku();
Kaizoku(std::string name, int hitPoints, int stamina, int speed);
void print();
void save(std::string fileName);
void load(std::string fileName);
private:
std::string dName;
int dHitPoints;
int dStamina;
int dSpeed;
};
#endif
Heres the class implementation:
#include "Kaizoku.h"
#include <iostream>
using namespace std;
Kaizoku::Kaizoku()
{
this->dName = "Default";
this->dHitPoints = 0;
this->dStamina = 0;
this->dSpeed = 0;
}
Kaizoku::Kaizoku(string name, int hp, int stamina, int speed)
{
this->dName = name;
this->dHitPoints = hp;
this->dStamina = stamina;
this->dSpeed = speed;
}
void Kaizoku::print()
{
cout << "Kaizoku Name: " << this->dName << endl;
cout << "HP: " << this->dHitPoints << endl;
cout << "Stamina: " << this->dStamina << endl;
cout << "Speed: " << this->dSpeed << endl <<endl;
}
void Kaizoku::save(string fileName)
{
ofstream oFile(fileName,ios_base::binary);
oFile.clear();
if(oFile)
{
oFile.write((char*)this,sizeof(Kaizoku));
oFile.close();
}
}
void Kaizoku::load(string fileName)
{
ifstream iFile(fileName,ios_base::binary);
if(iFile)
{
iFile.read((char*)this, sizeof(Kaizoku));
iFile.close();
}
}
And heres my main:
#include <iostream>
#include <string>
#include "Kaizoku.h"
using namespace std;
int main()
{
Kaizoku ka0("Name1",20,15,20);
Kaizoku ka1("Name2",18,17,18);
Kaizoku ka00;
Kaizoku ka11;
ka0.print();
ka00.print();
ka0.save("kaizoku.txt");
cout << "AFTER SAVE" << endl;
ka00.load("kaizoku.txt");
ka00.print();
}
The program loads and saves fine, the problem i got is that it crashes at the end of the application and i have no idea why?