views:

80

answers:

1

Hello everyone!

I am writing a high-score sub-routine for a text-based game. Here's what I have so far.

void Game::loadHiScores(string filename)
{
    fstream hiscores(filename.c_str()); // what flags are needed?
    int score;
    string name;
    Score temp;

    if (hiscores.is_open())
    {
        for (size_t i = 0; i < TOTAL_HISCORES && !(hiscores.eof()); ++i)
        {
            cin >> score >> name;
            temp.addPoints(score);
            temp.scoreSetName(name);
            hiScores.push_back(temp);
        }
    }
    else
    {
        //what should go here?
    }   

    hiscores.close();

}

How can I make it so that:

IF the file exists, it shall be open for reading

ELSE the file shall be created

Thanks for your time

+5  A: 

Wrong logic I would say. I think you want:

Try to open an ifstream (not an fstream) containing scores
if it opened
   read high scores into array
   close stream
else
   set array to zero
endif

Play Game - adjust high scores in array, then on exit

Try to open scores ofstream (not an fstream) for writing
if it opened
    write high scores
    close stream
else
    report an error
end if

If you use ifstreams and ofstreams, there is no need for special flags, or for possibly having to seek within the file - you just rewrite the whole thing.

anon
Thank you very much.
Francisco P.