2010-05-14 44 views
3

我正在爲基於文本的遊戲編寫高分子程序。這是迄今爲止我所擁有的。Beginner C++ - 打開一個文本文件進行閱讀(如果沒有的話),創建它爲空

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

} 

我怎樣才能讓這個:

如果該文件存在,它應開放閱讀

ELSE應創建

感謝您的時間文件

回答

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,沒有必要爲特殊標誌,或可能不必在文件中尋找 - 你只是重寫了整個事情。

+0

非常感謝。 – 2010-05-14 14:21:45