SFML community forums

Help => System => Topic started by: OutlawLee on September 18, 2012, 06:30:26 pm

Title: Input/output with files help
Post by: OutlawLee on September 18, 2012, 06:30:26 pm
I am trying to save player data to a txt file in the follownig format, but the problem is that i dont know how to save a single stat(ex. playerclass), and i dont know how to load into variables. Help!!


void Engine::SaveCharacterData(string PlayerName, int PlayerGender, int PlayerClass, int PlayerSkin)
{
    ofstream myfile ("Player1.txt");
    if (myfile.is_open())
    {
        myfile <<"Name:"<< PlayerName;
        myfile <<"Gender:"<< PlayerGender;
        myfile <<"Class:"<< PlayerClass;
        myfile <<"Skin:"<< PlayerSkin;
        myfile.close();
    }
    else
        cout << "Unable to open file";
}

void Engine::SaveCharacterClass(int PlayerClass)
{
    string curLine;

    ofstream myfile ("Resources/Saved_data/Player1.txt");
    if (myfile.is_open())
    {
        getline(myfile, curLine);
        if(curLine == "Class=")
        {
            myfile << PlayerClass;
        }
        myfile.close();
    }
    else
        cout << "Unable to open file";
}
Title: Re: Input/output with files help
Post by: FRex on September 18, 2012, 06:35:14 pm
What is exactly the problem and why doesn't it have anything to do with sfml?
Title: Re: Input/output with files help
Post by: OutlawLee on September 18, 2012, 06:39:12 pm
I need someone to make me or tell me how to write to specif line.
Hm now that you say i doesnt really have anything with sfml, asides that im using sfml to make a game.


Please help.
Title: Re: Input/output with files help
Post by: eXpl0it3r on September 18, 2012, 10:06:57 pm
There are many ways to load and save data and each and everyone has to fit with the data.
We won't gonna code stuff for you.
You'll have to try it on your own or use existing solutions (google will help you).
Title: Re: Input/output with files help
Post by: fallahn on September 18, 2012, 10:11:20 pm
You could create a struct to hold player data which you load from file at startup, modify during runtime, and write out to a file when necessary. This (http://forums.codeguru.com/showthread.php?269648-C-Structure-How-do-I-write-a-structure-to-a-file) should be a good place to start.
Title: Re: Input/output with files help
Post by: mateandmetal on September 19, 2012, 07:51:26 am
myfile <<"Name:"<< PlayerName;
myfile <<"Gender:"<< PlayerGender;
 

This code will create a file that looks like this
Name:GeorgeGender:10
 

When you save to the file, just insert a blank space or return character after the value, like this

myfile <<"Name:"<< PlayerName << std::endl;
myfile <<"Gender:"<< PlayerGender << std::endl;
 

Now the saved file will look like this
Name:George
Gender:10
 

To load data, just get the string from the ":" character to the end using substr (http://www.cplusplus.com/reference/string/string/substr/)