Question

I'm making a game and I have stored the map data in a 2-dimensional array of size [34][10]. Originally I generated the map using a simple function to fill up the array and saved this data to a file using the following code:

ofstream myFile;
myFile.open("map.txt");

for ( int y = 0 ; y < MAP_HEIGHT ; ++y )
{
    for ( int x = 0 ; x < MAP_WIDTH ; ++x )
    {
        myFile << m_acMapData[x][y];
    }
    myFile << '\n';
}

myFile.close();

This outputs a text file which looks something like how I want it to. However, when I try to read it back in using the following code, I get a load of access violations and it crashes at runtime:

ifstream myFile;
int i=0;
int j=0;
char line[MAP_WIDTH];

myFile.open("map.txt");
while (!myFile.eof())
{
    myFile.getline(line, MAP_WIDTH);
    for ( i=0; i<MAP_WIDTH; i++ )
    {
        m_acMapData[i][j] = line[i];
    }
    ++j;
    cout << line;
}

Does anyone know what the problem is?

Was it helpful?

Solution

while (!myFile.eof())
{
        myFile.getline(line, MAP_WIDTH);

should be:

while ( myFile.getline(line, MAP_WIDTH) )
{

It would however be safer to read into a std::string:

string line:
while ( getline( myFile, line ) )
{

You might also want to read my blog on this subject, at http://punchlet.wordpress.com.

OTHER TIPS

Ya i will definately crash because you are doing wrong here.

ofstream myFile;
myFile.open("map.txt");

for ( int y = 0 ; y < MAP_HEIGHT ; ++y ) 
{
    for ( int x = 0 ; x < MAP_WIDTH ; ++x )
    {
            myFile << m_acMapData[x][y];
    }
    myFile << '\n';
}
myFile.close();

Suppose MAP_HEIGHT = 3 and MAP_WIDTH = 6 ;

And you must know that array in C/C++ is row major so when you try to access

m_acMapData[4][0] it would accessing memory out of its range.

So do something like this:

for ( int y = 0 ; y < MAP_HEIGHT ; ++y ) 
{
    for ( int x = 0 ; x < MAP_WIDTH ; ++x )
    {
            myFile << m_acMapData[y][x]; // here to be changed
    }

    myFile << '\n';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top