File Input and Output with C++

Recommended Posts

Hi, i was just playing around with doing file input and putput with C++ and was wondering how I would go about loading the information from my file. I have a file called char.sav that I will be putting information into, the format of the file will be as follows **Start of char.sav** Character Name Health Left/Max Health Mana Left/Max Mana Strength Defense Speed Stamina Agility Gold Current Experience/Experience Required so the first line of the file would have the character name, second line would have the health left and maximum health, third would have mana left and max mana and so on... now how would I go about loading each piece of information to be able to save it for use in my file? Thanks for any help, and if anything is unclear just let me know and I will try to clear it up.

Share on other sites
vtchill    180
I am not completely sure this is what you are asking for but for saving character stuff to a file you could do something similar to this:

void SaveCharacterInfo(const Character& myChar){	std::ofstream outputFile("char.sav");	if (outputFile)	{		std::ostringstream oss;				oss << myChar.GetName() << std::endl;		oss << myChar.GetHealth() << std::endl;		oss << myChar.GetMaxHealth() << std::endl;		oss << myChar.GetMana() << std::endl;		oss << myChar.GetMaxMana() << std::endl;		oss << myChar.GetStrength() << std::endl;		oss << myChar.GetDefense() << std::endl;		oss << myChar.GetSpeed() << std::endl;		oss << myChar.GetStamina() << std::endl;		oss << myChar.GetAgility() << std::endl;		oss << myChar.GetGold() << std::endl;		oss << myChar.GetExperience() << std::endl;		oss << myChar.GetMaxExperience() << std::endl;			outputFile << oss.str();		outputFile.close();	}}

Reading in the data is similar also just open up an std::ifstream object to the file and iterate through it using ">>" operator to get each field.

I have not tested or compiled any of this code, but it shows the basic idea.

Good luck

Share on other sites
kiome    229
It might be useful to understand the concept of serialization which would serve you well in such a case.
The boost library has already a template solution for such functionality and the website provides a tutorial for it.