【问题标题】:Beginner C++ - Opening a text file for reading if it exists, if it doesn't, create it empty初学者 C++ - 如果存在则打开一个文本文件进行读取,如果不存在,则将其创建为空
【发布时间】:2010-05-14 13:44:01
【问题描述】:

我正在为基于文本的游戏编写高分子程序。这是我目前所拥有的。

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

}

我怎样才能做到:

如果文件存在,则应打开以供阅读

否则将创建文件

感谢您的宝贵时间

【问题讨论】:

    标签: c++ text text-files fstream


    【解决方案1】:

    我会说错误的逻辑。我想你想要:

    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,则无需特殊标志,也无需在文件中查找 - 您只需重写整个内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-31
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多