CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 3 123 LastLast
Results 1 to 15 of 34
  1. #1
    Join Date
    Oct 2013
    Location
    Maysville, KY
    Posts
    18

    Save/load functions not working

    Hi. I've been working on a battle simulator, and using it as a learning experience. So far, I've been able to debug the program(with some help), and learn some stuff, and it's been running smoothly. It's still runnable, but I've been trying to make it so the player can save his character, and continue the game later. However, I'm not sure whether it's the save or load function that's not working, because even if i save to a txt file, it's just a bunch of random characters. I don't know if that means it's not saving correctly, or if it's just supposed to be like that. Anyway, here are the two functions I'm speaking of:

    Code:
    void Game::saveGame(Character &player)
    {
        std::ofstream saveFile("save.bin", ios::binary);
        saveFile.write((char *)&player, sizeof(player));
        saveFile.close();
    }
    
    void Game::loadGame()
    {
        std::ifstream loadFile("save.bin", std::ios::binary);
        Character player;
        loadFile.read((char *)&player, sizeof(player));
        startGame(player);
        loadFile.close();// needs player info
    }
    Can anyone identify the problem from this? My program is in multiple files, so I can't really post the whole code easily, but I can upload or something if I really need to.

  2. #2
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: Save/load functions not working

    Quote Originally Posted by KruSuPhy View Post
    However, I'm not sure whether it's the save or load function that's not working, because even if i save to a txt file, it's just a bunch of random characters. I don't know if that means it's not saving correctly, or if it's just supposed to be like that.
    That's because you are saving a memory address as a binary value in the file. Once your process ends, the memory will be reused by the OS, so the next time you start your process, that pointer has become meaningless. Even if you read it back in from the file, you can do nothing with it.

    To serialize an object, you need to read/write each piece of information stored in that object (typically each member variable). The read and write member functions of std::stream just read/write a bunch of bytes. It's probably best to use the overloaded >> and << operator to read to and write from a stream, resp. Any introductory book about C++ will teach this.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  3. #3
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Save/load functions not working

    Quote Originally Posted by KruSuPhy View Post
    However, I'm not sure whether it's the save or load function that's not working, because even if i save to a txt file, it's just a bunch of random characters. I don't know if that means it's not saving correctly, or if it's just supposed to be like that.
    If what you see in the file is gibberish, then you didn't save correctly. Reading gibberish will not turn it into any coherent.

    D_Drmmr gave the reason for the issue -- you must save data to a file, not a pointer. Saving data means just that -- for example, if it's a string you're saving, then you must save the characters that make up the string.

    Regards,

    Paul McKenzie

  4. #4
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: Save/load functions not working

    I don't see where a pointer is being saved to file.

    If the Character class is POD, then the posted code is correct.
    If the Character class contains non-POD variables (such as std::string)
    or pointers then the posted code will not work.

    Binary is often used for large files where its speed advantage is large
    over text files. I doubt that your file is very large. It would be easier
    to verify the writing and to get it correct if you do not use binary.

  5. #5
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Save/load functions not working

    Quote Originally Posted by KruSuPhy View Post
    However, I'm not sure whether it's the save or load function that's not working, because even if i save to a txt file, it's just a bunch of random characters. I don't know if that means it's not saving correctly, or if it's just supposed to be like that.
    To advise further, please post the class definition of Character. As Philip states in post #4, if the class just contains in-built types such as int and char then your code is OK (even if looks weid in a text editor!). If it contains pointers (eg char *) or other classes (eg string, vector etc) then the code won't work properly.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  6. #6
    Join Date
    Oct 2013
    Location
    Maysville, KY
    Posts
    18

    Re: Save/load functions not working

    Quote Originally Posted by 2kaud View Post
    To advise further, please post the class definition of Character. As Philip states in post #4, if the class just contains in-built types such as int and char then your code is OK (even if looks weid in a text editor!). If it contains pointers (eg char *) or other classes (eg string, vector etc) then the code won't work properly.
    I am currently not at home, and cannot post the code from my program, but I am using pretty much a replica of the code that PredicateNormative posted in my previous thread (http://forums.codeguru.com/showthrea...ll-battle-game)
    I'm also using the method of saving and loading that I got from this website(http://www.functionx.com/cpp/articles/serialization.htm).
    If the problem is that I use std::string, would I fix that by switching it to a character array?

  7. #7
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Save/load functions not working

    If you are using std:string in the class, then your save/load code won't work. If you use a character array (not a character pointer) in the class then the code should work.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  8. #8
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Save/load functions not working

    Quote Originally Posted by KruSuPhy View Post
    If the problem is that I use std::string, would I fix that by switching it to a character array?
    Then you open up your code to an issue of buffer overrun if you now switch your struct to using char arrays.

    The issue is that you used a link that shows how to save 'C'-style or POD (Plain Old Data) structures. The types in the example code you linked to are simple types, i.e. int, double, etc. Look at the class you created -- it contains non-simple (non-POD) types, namely std::string.

    So the bottom line is that you can't "mass-copy" a struct or class that contains non-POD types as the example shows you. You have to properly serialize the data, and that means copying the items to the file, one-by-one in a coherent manner, so that when it comes time to read the file, you read it back correctly. This means that std::string must store the character string within the file.

    Regards,

    Paul McKenzie

  9. #9
    Join Date
    Oct 2013
    Location
    Maysville, KY
    Posts
    18

    Re: Save/load functions not working

    So, should I use something like this, then?
    Code:
    SaveGame(FileInput file) {
        file.writeInt(playerLevel);
        file.writeInt(playerHealth);
        file.writeInt(gameProgress);
    }
    
    LoadGame(FileInput file) {
        if(file.exists()) {
            playerLevel= file.readInt();
            playerHealth = file.readInt();
            gameProgress = file.readInt();
        } else {
            playerLevel = 1;
            playerHealth = 100;
            gameProgress = 0;
        }
    }

  10. #10
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: Save/load functions not working

    Quote Originally Posted by Philip Nicoletti View Post
    I don't see where a pointer is being saved to file.
    You're right. My bad.
    Quote Originally Posted by KruSuPhy View Post
    So, should I use something like this, then?
    Please post complete examples that will compile when copy-pasted into a compiler. Functions in C++ must have a return type; your's don't. We also don't know what FileInput is.

    When you try to learn something new in C++, it's best to start with a small example to get familiar with the topic before using those techniques in an existing program. Just write a simple program that writes an int, a double and a string to a file and reads it back. Then adapt the program to write one or more instances of a struct/class containing multiple variables. Only when you understand the topic, can you apply it to an existing program. That way, your test programs will be small enough for you (and anyone here) to understand completely. And you can post the full code of the program by just copy-pasting.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  11. #11
    Join Date
    Oct 2013
    Location
    Maysville, KY
    Posts
    18

    Re: Save/load functions not working

    Sorry, the example was pseudo-code someone suggested in another topic on another website. I'm afraid I don't have or know the complete code for that method, I was just wondering if there is a method like that, and what it is, if so.
    Anyway, thanks for the tip. I normally do that anyway when I'm studying a new concept, but I got a little cocky and decided not to when working with file i/o. However, I'll go back and work on something like that now.

  12. #12
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Save/load functions not working

    Quote Originally Posted by KruSuPhy View Post
    Sorry, the example was pseudo-code someone suggested in another topic on another website. I'm afraid I don't have or know the complete code for that method,
    Next time, it would help to point that out, or better yet post your real, actual code so we don't all waste our time.

  13. #13
    Join Date
    Oct 2013
    Location
    Maysville, KY
    Posts
    18

    Re: Save/load functions not working

    Quote Originally Posted by GCDEF View Post
    Next time, it would help to point that out, or better yet post your real, actual code so we don't all waste our time.
    Okay, I apologized for it. Don't get an attitude in my thread, you haven't even contributed in the slightest amount, thanks. If you don't have anything worthwhile to say, then don't post.
    Last edited by KruSuPhy; October 19th, 2013 at 11:39 AM.

  14. #14
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Save/load functions not working

    Quote Originally Posted by KruSuPhy View Post
    Okay, I apologized for it. Don't get an attitude in my thread, you haven't even contributed in the slightest amount, thanks. If you don't have anything worthwhile to say, then don't post.
    I'll post in any thread I feel like posting in. If you post specific code, people will assume that's the code you're using and base their answers accordingly. It doesn't do you any good either to get specific answers that don't apply to your specific code.

  15. #15
    Join Date
    Oct 2013
    Location
    Maysville, KY
    Posts
    18

    Re: Save/load functions not working

    Quote Originally Posted by GCDEF View Post
    I'll post in any thread I feel like posting in. If you post specific code, people will assume that's the code you're using and base their answers accordingly. It doesn't do you any good either to get specific answers that don't apply to your specific code.
    Post if you want, but at least try to provide some useful information as opposed to getting upset over something I've already apologized for.
    Also, I'm sorry that I'm not exactly knowledgable in C++ question-asking etiquette, I am, and I emphasize this, a beginner. I don't have specific code for that method, I was merely asking if there is a method similar to that pseudo-code, and whether or not I should use it if there is.

Page 1 of 3 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured