Sign in to follow this  

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 this post

Link to post
Share on other sites
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();

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 this post

Link to post
Share on other sites
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.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this