【问题标题】:Errors with Saving/Loading C++ Data保存/加载 C++ 数据时出错
【发布时间】:2017-01-25 03:47:31
【问题描述】:

所以我在这里用 C++ 开发这个小资源收集游戏。与游戏(已开发)相关的所有内容都运行良好……但是,保存和加载进度对我来说似乎是个大问题。

我使用了几种不同的方法,在放弃了一些自定义内容(命名您的保存文件)之后,我得到了保存。但是现在,加载时,似乎让'wood'变量有一个很大的数字,而石头,名称等东西都被忽略了。

代码:

  • 保存

    ofstream saveFile;
    saveFile.open("save.save");
    saveFile << wood << stone << iron << gold << hasHatchet << hasPickaxe << hasDrill << hasPlasma_Cutter << hatchetLevel << pickaxeLevel << drillLevel << pcutterLevel << name;
    saveFile.close();
    
  • 加载中

    ifstream loadFile;
    loadFile.open("save.save");
    loadFile >> wood >> stone >> iron >> gold >> hasHatchet >> hasPickaxe >> hasDrill >> hasPlasma_Cutter >> hatchetLevel >> pickaxeLevel >> drillLevel >> pcutterLevel >> name;
    loadFile.close();
    goto mainProg;
    
  • 变量(供参考)

    int wood = 0;
    int stone = 0;
    int iron = 0;
    int gold = 0; // Resource variables
    bool hasHatchet = true;
    bool hasPickaxe = false;
    bool hasDrill = false;
    bool hasPlasma_Cutter = false; // Tool boolean values
    int hatchetLevel = 1;
    int pickaxeLevel = 0;
    int drillLevel = 0;
    int pcutterLevel = 0; // Tool level variables
    string name = "";
    

【问题讨论】:

标签: c++ save loading


【解决方案1】:

这是因为你保存这些变量时没有空格,所以 save.save 将包含字符串000010001000。当它被加载时,程序会将这些字符串识别为木头,这使得木头变量具有那些大的数字

在保存的同时尝试用空格分隔变量

saveFile &lt;&lt; wood &lt;&lt; " " &lt;&lt; stone &lt;&lt; " " &lt;&lt; iron &lt;&lt; " " &lt;&lt;gold;

【讨论】:

  • @Matt 注意endl。它是一个换行和一个流刷新到底层媒体,在这种情况下是一个文件。这是一项极其昂贵的操作,因为每次添加项目时都会写入文件,而不是缓冲数据,并且只在需要时才将缓冲区写入文件。为了便于目视检查文件以进行调试,我建议使用类似于 Arianto 的建议的内容:saveFile &lt;&lt; wood &lt;&lt; " " &lt;&lt; stone &lt;&lt; " " &lt;&lt; iron &lt;&lt; " " &lt;&lt;gold &lt;&lt; '\n'; 最后的换行符在视觉上将一组与下一组分开,并且不会强制刷新。
猜你喜欢
  • 2016-04-13
  • 1970-01-01
  • 1970-01-01
  • 2020-01-30
  • 1970-01-01
  • 1970-01-01
  • 2012-05-31
  • 2015-10-17
  • 1970-01-01
相关资源
最近更新 更多