You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++游戏项目结构体文件加载异常:仅加载前25个对象求助

问题分析与解决方案

核心问题1:结构体指针存储导致的读取异常

你代码里的const char* type是致命问题——保存文件时,写入的是指针的内存地址而非字符串本身。加载时这个地址在当前进程中是无效的,不仅读不到正确的类型字符串,还会破坏流状态,直接导致后续读取提前终止(这就是只能读25个对象的原因)。

必须把指针改成固定大小的字符数组,确保字符串内容被直接写入文件:

struct GameObject {
    char type[32]; // 数组大小可根据需求调整
    int sizeW;
    int sizeH;
    int collisionLayer;
    int textureID;
    int positionX;
    int positionY;
} loadStruct;

核心问题2:while (!eof())的错误用法

eof()只有在读取失败后才会返回true,原代码的最后一次循环会执行一次无效读取(此时已到文件末尾,但循环条件仍成立),可能引发错误或异常。正确做法是把读取操作直接放在循环条件里。

修正后的完整加载代码

#include <fstream>
using namespace std;

struct GameObject {
    char type[32];
    int sizeW;
    int sizeH;
    int collisionLayer;
    int textureID;
    int positionX;
    int positionY;
} loadStruct;

int main() {
    ifstream fileObj("level.txt", ios::binary); // 必须加ios::binary,避免文本模式的换行转换干扰
    if (fileObj.is_open()) {
        // 流状态有效时继续循环,读取失败自动终止
        while (fileObj.read((char*)&loadStruct, sizeof(loadStruct))) {
            // 用loadStruct创建游戏对象的逻辑
        }
        fileObj.close();
    }
    return 0;
}

更可靠的进阶方案:先存储对象总数

如果想彻底避免循环终止的不确定性,可在保存文件时先写入对象总数量,加载时先读取该数值,再循环对应次数,这是游戏开发中常用的可靠做法:

保存时的代码示例

ofstream outFile("level.txt", ios::binary);
if (outFile.is_open()) {
    int objCount = gameObjects.size(); // 假设gameObjects是你的对象列表
    outFile.write((char*)&objCount, sizeof(objCount));
    for (const auto& obj : gameObjects) {
        outFile.write((char*)&obj, sizeof(obj));
    }
    outFile.close();
}

加载时的代码示例

ifstream fileObj("level.txt", ios::binary);
if (fileObj.is_open()) {
    int objCount;
    fileObj.read((char*)&objCount, sizeof(objCount));
    for (int i = 0; i < objCount; ++i) {
        fileObj.read((char*)&loadStruct, sizeof(loadStruct));
        // 创建游戏对象
    }
    fileObj.close();
}

内容的提问来源于stack exchange,提问作者BigAgg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:50:25