Saving 2D Char arrays to file in C++

0

So in my program I have a 2d character array gameField that has various characters stored in it to represent forts, the player, empty space, and a home base. I am trying to save this array into a file, but the way that I am trying to do is do not seem to be working. This is my sample code.

void saveMap()
{
    string userMap = directoryName + username + "-map.txt";
    ofstream savemap(userMap.c_str());

    for (int i = 0; i <= ROWS; i++)
    {
        for (int j = 0;j <= COLUMNS; j++)
        {
            savemap << gameField[i][j];
        }

        savemap << endl;
    }

    savemap.close();
 }

I keep getting run-time errors whenever I try and execute this, I was wondering if anyone could explain why and perhaps offer an alternative.

EDIT: gameField is a character array, COLUMNS is equal to 50 and ROWS is equal to 30. I have every single character in the array initialized and set equal to something, but whenever I call the function I'm getting a Unhandled exception at 0x511cbe20 (msvcr100d.dll) in Game1.exe: 0xC0000005: Access violation reading location 0x30303030.

c++
asked on Stack Overflow May 13, 2014 by Duyve • edited Feb 13, 2016 by marc_s

1 Answer

2

You are trying to access memory beyond the array. For example the valid range for rows is [0, ROWS - 1]

I would write the function the following way

void saveMap()
{
   string userMap= directoryName+username+"-map.txt";

   ofstream savemap(userMap.c_str());

   int i = 0;

   while ( i < ROWS && savemap.write( gameField[i++], COLLUMS ) ) savemap << std::endl;
}
answered on Stack Overflow May 13, 2014 by Vlad from Moscow

User contributions licensed under CC BY-SA 3.0