# C++ Saving and Loading From Text File

In my C++ program I am trying to develop a simple saving and loading function for my game. I can easily get the save function on it, but the loading part of it really stumps me.

What I need is to load the numbers on the file (line by line) and insert them into different variables for my player. I'm just not able to figure that out. I've even looked all around the inter webs.

Here is the code for the player save and load functions:

void Player::Save()
{
std::ofstream savePlayerFile;
savePlayerFile.open("Save/playerSave.dat", std::ofstream::trunc);

savePlayerFile << x << "\n" << y << "\n" << prevX << "\n" << prevY << "\n" << health << "\n" <<
health  << "\n" <<  mana  << "\n" <<  gold  << "\n" <<  level  << "\n" <<  maxHealth << "\n" <<
maxMana << "\n" << strength << "\n" << defense;

savePlayerFile.close();
}

{

/*std::string line;
{
std::istringstream iss(line);
*/
loadPlayerFile >> ( x && "\n" && y && "\n" && prevX && "\n" && prevY && "\n" && health && "\n" &&
health && "\n" && mana && "\n" && gold && "\n" && level && "\n" && maxHealth && "\n" &&
maxMana && "\n" && strength && "\n" && defense);
}

• Possible resource here and here. Basically, instead of \n for writing, use spaces (" "), and in reading, remove the (/), replace && by >>, and remove all "\n": loadPlayerFile >> x >> y >> prevX >> prevY >> [...]; Jul 9 '15 at 23:47
• You'll have an easier time writing a binary file! Jul 10 '15 at 3:23
• @AlexandreVaillancourt Thanks So Much! The way you told me to do it worked out great! Jul 10 '15 at 5:43
• @AlanWolfe I might try and take that on. It seems interesting. Jul 10 '15 at 5:43

I highly recommend serialization as well, whether you use boost or your own magic.

But, if you want to keep it simple for maybe prototyping sake, you could use streams like you are. You could even make this really easy on yourself and do space delimited. Since you know the format your saving, you simply have to parse it back the same way into whatever vars you want.

For example:

save() {
stream << health << mana;
}