数据未保存在文本文件中(C++ Fstream 库)
Data isn't being saved in the text file (C++ Fstream library )
我一直试图将游戏中玩家的分数保存在文本文件中,但它没有这样做。这是我正在使用的代码:
//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()
的调用;析构函数将关闭该文件。
相关文章:
- 在fstream期间忽略空行
- 使用fstream对txt文件中的数字进行循环
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- 使 std::fstream 写入文件末尾,但从头开始读取
- 为什么当我在 std::string 中打开文件名的 fstream 时出现"no matching function"错误?
- 自定义 std::fstream,std::filebuf 的溢出和下溢函数未为每个字符调用
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- fstream / ifstream / ofstream 对象如何转换为布尔值
- 使用命令的未定义引用<fstream>
- 如何检查文件是否已存在于 fstream C++中
- 如何正确使用 fstream 并在 char 数组中传递数据?
- 如何使用 fstream 的 .get 字符串?
- 使用 fstream 库并在屏幕上打印的文件有问题?
- Windows std::fstream 修改文件后打开()?
- 如何删除文件中的数字,通过 c++ fstream 的
- std::fstream 在 MSVC 和 G++ 上使用 UTF-8 的不同行为
- C++ 错误检查 fstream open() 命令和一般字符串流错误处理
- 在istream_iterator中使用后的 C++ FSTREAM obj 回滚
- 如何使用单个fstream创建、读取和写入文件