Pergunta

I'm writing a simple sandbox text-based game in c++ and have just got around to save files. Having looked at a few of the questions on this site and others I opted to do my own rather that use the boost libraries etc.

My save code works fine however, my load code isn't working like I want!

int loadGame(string filename){
string delim=":";
string readline;

ifstream filestream;
filestream.open(filename.c_str());

while(getline(filestream,readline)){
    cout << readline << endl;
    stringstream linestream(readline);
string         data;
getline(linestream, data, ':');
linestream >> playername >> location[0] >> location[1] >> hitpoints >> coins >> axes >> swords >> food >> maps;
}
return 0;
}

It currently loops, as you would expect but then stores only the last 'maps' variable to playername. I understand that the while(getline(filestream,readline)){ is the cause of the problem but as a newbie I can't see how to work around this without adding in a loop with lots of ifs that does an (pseudo code)

while(n<10){
if n=1{ linestream >> playername}
if n=2{linestream >> location[0]...

which seems to me to be very drawn out and inefficient.

A sample save might look like this:

playername:John
location[0]:400
location[1]:840
hitpoints:100
coins:35
axes:0
swords:0
food:0
maps:3

I know this is probably badly worded but I'd appreciate any help on this problem. Thanks in advance. ps any other tips on the code posted here would be great :)

Foi útil?

Solução

If you're beginning with C++, there are a couple of tips I could give you.

First of all, don't bother with parsing. There are far more interesting things to do with your time. Choose an easier input format, like

playername John Doe
hitpoints 300

Notice that I'm using a white space to separate the value from the key. Now you can simply do something like:

std::string key, value;
while (<more input>)
{
    input_file >> key;
    std::getline(input_file, value);

    if (key == "playername")
        // whatever...
    else if (key == "maps")
        // stuff...
}

Outras dicas

In the loadGame function you are checking unknown "arg" to string "null", not NULL.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top