Thread: SaveGame and LoadGame.

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    56

    SaveGame and LoadGame.

    Hi, i am creating a little c++ rpg game and now i have trouble with saving and loading data.

    Saving Game:
    For saving game, i just have to output all the info of my hero to a txt file. To do that, i use something like this:

    ifstream myFile;
    ofstream outfile;

    Code:
    outfile.open("SaveLoadgame.txt");
    ...
    ...
    outfile<<name<<endl<<stamina<<endl<<hp<<endl;
    Loading Game:
    For loading game i read into the same txt file(which i think i cannot do that)
    Code:
    myFile.open("SaveLoadgame.txt");
    ...
    ...
    myFile>>name;
    myFile>>stamina;
    myFile>>hp;
    ...
    But the problem is after saving the game and close it, then i restart it , my txt file automatically become blank. Therefore there are nothing to load....

    I think i cannot use the same txt file name.
    Is that another method to do that?

  2. #2
    Registered User
    Join Date
    Dec 2002
    Posts
    221
    are u closing the file after u write to the file?

  3. #3
    Registered User
    Join Date
    Oct 2002
    Posts
    56
    yes of course, because i want to play that game later...

  4. #4
    Registered User
    Join Date
    Oct 2002
    Posts
    56
    i'm thinking if i can do something like this:

    1.Create 2 txt files (SaveGame.txt, LoadGame.txt)

    2. Save the hero's info to SaveGame.txt

    3.Copy data in SaveGame.txt to LoadGame.txt(I don't know to do that)

    4.Load hero's info by reading LoadGame.txt

    By doing this, it become:
    Code:
    myFile.open("LoadGame.txt")
    outfile.open("SaveGame.txt")
    ...
    ...
    instead of opening the same file(maybe the reason that gave a blank text file each time execute the game):
    Code:
    myFile.open("SaveLoadgame.txt");
    outfile.open("SaveLoadgame.txt");
    ...
    ...

    any ideas?

  5. #5
    t_rex
    Guest
    Try this,

    Code:
    #include <iostream>
    #include <fstream.h>
    using namespace std;
    int main()
    {
    int hp = 32;
    int stamina = 87;
    
    int newhp = 0;
    int newstamina=0;
    
    cout<<endl<<endl<<"HP value is "<<newhp<<" before load"<<endl;
    cout<<"Stamina value is "<<newstamina<<" before load"<<endl<<endl;
    
    ofstream dataexport("data.txt");
    
            dataexport
            <<hp<<endl
            <<stamina<<endl;
    
            dataexport.close();
    		cout<<"Data export complete."<<endl<<endl;
    
    ifstream dataimport("data.txt");
             dataimport
             >>newhp
             >>newstamina;
             dataimport.close();
    
             cout<<"Data import complete."<<endl<<endl;
    
             cout<<"New HP value is "<<newhp<<endl;
             cout<<"New Stamina value is "<<newstamina;
    
          return 0;
    }

Popular pages Recent additions subscribe to a feed