数据未保存在文本文件中(C++ Fstream 库)

Data isn't being saved in the text file (C++ Fstream library )

本文关键字:C++ Fstream 文件 保存 存在 文本 数据      更新时间:2023-10-16

我一直试图将游戏中玩家的分数保存在文本文件中,但它没有这样做。这是我正在使用的代码:

//some code above 
std::fstream TextScore ("Ranking.txt");

// some code above
if (Player->getFinal(Map) == true)
    {
        TextScore.open("Ranking.txt", ios::out);
        TextScore << Player->getPoints();
        TextScore.close();
        //some code below
    }

然后我检查文本文件,什么都没有保存,文件是空的。我想知道我错过了什么或做错了什么。

提前谢谢。

std::fstream TextScore ("Ranking.txt");

这将打开文件,就像调用TextScore.open("Ranking.txt"), std::ios::in|std::ios::out)一样。

TextScore.open("Ranking.txt", std::ios::out);

这将再次打开它。

如果文件已存在,则组合将不起作用。第一次打开将成功,第二次打开将失败。之后,所有 I/O 操作都将失败。只需在构造函数中或在单独的open调用中打开一次。最惯用的C++方式是

{
  std::fstream TextScore ("Ranking.txt", std::ios::out);
  TextScore << Player->getPoints();
}

由于 RAII,无需显式关闭文件。

打开同一个文件两次肯定会引起问题。将TextScore的定义移到 if 语句的正文中,以代替对TextScore.open()的调用。然后您可以删除对TextScore.close()的调用;析构函数将关闭该文件。