Search code examples
c++filefile-iofstreamaccess-violation

Loading text from a file into a 2-dimensional array (C++)


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?


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.