Hi
I am currently working through some C++ tutorials. I have hit a bug in trying to answer one exercise. Mycode seems to work but I get an unhandled exception as the program terminates. This happens when running it from inside Visual Studio and when I try to run it from the command prompt. I cannot see where the unhandled exception is coming from. My method seems to read in the binary data ok and the execrcise to write the file seems to work ok too. The binary file is created running main in main1.cpp. It is when the program generated from using main2.cpp terminates that I get the unhandled exception. Any help is appreciated.
Here is all the code
// Wiz.h
#ifndef WIZARD_H
#define WIZARD_H
#include <fstream>
#include <string>
class Wizard
{
public:
Wizard();
Wizard(std::string, int hp, int mp, int armor);
void print();
void save (std::ofstream& outFile);
void load (std::ifstream& inFile);
private:
std::string mName;
int mHitPoints;
int mMagicPoints;
int mArmor;
};
#endif // WIZARD_H
// Wiz.cpp
#include "Wiz.h"
#include <iostream>
using namespace std;
// if the file is opened correctly call the save method of each wizard
if (outFile)
{
wiz0.save(outFile);
wiz1.save(outFile);
wiz2.save(outFile);
}
outFile.close();
}
// main2.cpp
#include "Wiz.h"
#include <iostream>
using namespace std;
int main()
{
// create some blank wizards
Wizard wiz0;
Wizard wiz1;
Wizard wiz2;
// Output Wizards before they are loaded.
cout << "BEFORE LOADING..." << endl;
wiz0.print();
wiz1.print();
wiz2.print();
// if the file opened correctly then call the load methods
if (inFile)
{
wiz0.load(inFile);
wiz1.load(inFile);
wiz2.load(inFile);
}
else
cout << "The file could not be opened!" << endl;
inFile.close();
// Output the wizards with their data
cout << "AFTER LOADING..." << endl;
wiz0.print();
wiz1.print();
wiz2.print();
because your Wizard class contains more than plain old data (it has a std::string as a member variable). What you should do is either a) save and load the member variables separately, and when it comes to saving the string, save its length (so you know how many chars to read back) followed by each char, or b) change the std::string to something like char[MAX_LENGTH] so that your current save and load routines work as is. Note that choice a) is preferable to b) as loading and saving as per your current implementation is dependent on the order of member variables in the Wizard class (i.e. if you change the order, then loading a saved file with a previous ordering will not work).