3

テキストベースのゲームのハイスコア サブルーチンを書いています。これが私がこれまでに持っているものです。

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();

}

次のようにするにはどうすればよいですか。

ファイルが存在する場合は、読み取り用に開かれます

それ以外の場合、ファイルが作成されます

御時間ありがとうございます

4

1 に答える 1

5

私が言う間違った論理。私はあなたが欲しいと思います:

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

ifstreams と ofstreams を使用する場合、特別なフラグやファイル内でシークする必要はありません。すべてを書き直すだけです。

于 2010-05-14T13:54:05.323 に答える