Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 数据不完整';t保存在文本文件(C+;+;流媒体库)中_C++_File_Fstream - Fatal编程技术网

C++ 数据不完整';t保存在文本文件(C+;+;流媒体库)中

C++ 数据不完整';t保存在文本文件(C+;+;流媒体库)中,c++,file,fstream,C++,File,Fstream,我一直试图将游戏中玩家的分数保存在文本文件中,但它没有这样做。 这是我正在使用的代码: //some code above std::fstream TextScore ("Ranking.txt"); // some code above if (Player->getFinal(Map) == true) { TextScore.open("Ranking.txt", ios::out); TextScore << Play

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

//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”,ios::out);
TextScore getPoints();
TextScore.close();
//下面是一些代码
}
然后我检查文本文件,没有保存任何内容,文件为空。 我想知道我错过了什么或做错了什么

提前谢谢

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();
}
{
std::fstream TextScore(“Ranking.txt”,std::ios::out);
TextScore getPoints();
}

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

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

您确定该语句甚至会执行(即如果
的条件得到满足,
)?它会编译,但文本文件仍然为空,这意味着分数没有保存在文本文件中。是的,它得到了满足。您确定要查找正确的文件吗?你确定它成功打开了吗?你能
cassert(TextScore.is_open())
确认你成功打开了Ranking.txt吗?谢谢。它可以工作,但现在它会覆盖分数。当然可以。您希望得到什么?也许可以尝试添加
std::ios::ate
。它不起作用。分数仍在被覆盖,它只显示最后保存的分数。请使用
std::ios::out | std::ios::app
附加到文件而不截断。谢谢。还有一个问题,分数被覆盖,因此它只显示保存的最后一个分数。我怎样才能解决这个问题?