How to create a Save/Load function for a text based game

Hi I just recently started learning c++ at the beginning of my college semester a couple months ago, and I liked it enough to attempt a text based game. It's going fairy well so far, but I wanted to know how to write a save/load function for stuff like health, current damage, current gold, etc. Any help is appreciated, thanks!

I'd also like to ask if it's possible to have a command you can type at any time that will display your current "stats," but the saving/loading is what I want more help with.
Last edited on
Maybe you have something like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
class Game {
  private:
    int gold;
  public:
    void load(const string &filename) {
      ifstream in(filename);
      in >> gold >> ws;
    }
    void save(const string &filename) {
      ofstream out(filename);
      out << gold >> '\n';
    }
};


In some outer layer of code running your game loop, you have some commands like load and save.

So for example, on typing 'load' at your prompt, you call
 
myGameObject.load("savegame.txt");
you have to save your rooms if they change, eg if room 3 has a pile of gold in it and you took it, you need to know it is gone. one way to do that is to give items a location (on player, in room number, etc) and save just that info. If there are bad guys, you may need to save where they are and such. the more complex the game the more you need to save... if there are puzzles, you have to save something there.. anything the player can interact with and change has to save its modified state somehow.
Topic archived. No new replies allowed.