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.
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;
}
User contributions licensed under CC BY-SA 3.0