SFML 2.0从映射文件加载

时间:2012-12-27 11:36:06

标签: c++ file map external sfml

好的大家好!我又遇到了另一个问题..我得到了一个未处理的异常。

我将问题追溯到它的来源:

openfile >> MapFile[loadCounterX][loadCounterY];

例外是:

Unhandled exception at 0x76ee15de in The Vanity Engine.exe: 0xC0000005: Access violation writing location 0x336e880c.

它说它违反了访问权限,但我正在访问的内容已在此处成功打开:

std::ifstream openfile(filename);

整个功能是:

//Load map
void Map::Load(const char *filename)
{
    //Open the file
    std::ifstream openfile(filename);
    //Check if file is open
    if(openfile.is_open())
    {
        //Get mapSizeX and Y from the file
        openfile >> mapSizeX >> mapSizeY;
        //While not at the end of the file
        while(!openfile.eof())
        {
            //Store number at loadCounterX and loadCounterY
            openfile >> MapFile[loadCounterX][loadCounterY]; //Error here
            //Increment loadCounterX++
            loadCounterX++;
            //If loadCounterX is less than mapSizeX
            if(loadCounterX >= mapSizeX)
            {
                //Set loadCounterX to 0
                loadCounterX = 0;
                //Increment loadCounterY 
                loadCounterY++;
            }
        }
    }
}

MapFile位于Map.H

#ifndef MAP_H
#define MAP_H

#include "SFML\Graphics.hpp"
#include "Global.h"
#include <iostream>
#include <fstream>

class Map
{
public:
    void Load(const char *filename);
    void Draw(sf::RenderWindow &Window);
private:
    int loadCounterX, loadCounterY;
    int mapSizeX, mapSizeY;
    int MapFile[100][100];
};

#endif

1 个答案:

答案 0 :(得分:1)

loadCounter*应该是本地的功能,或者每次加载时都至少初始化为0.

这是第一次可以正常工作,但是在下次加载之前变量不会重置为0,从而导致寻址未分配的空间。

旁注:

请为地图数据使用某种动态分配(例如std :: vector)。每次使用100x100都没有意义,是吗?