Search code examples
c++classiofstreamdynamic-memory-allocation

Output not matching input C++


I am trying to (right now anyway), to display a maze from a data file. The first grouping of numbers is the size, the second the entrance, and the third are for the exit coordinates.

I have a simple input file named "MyMaze1.dat":

7 20 
0 18
6 12
****************** *
*     *      ***** *
* ***** ***        *
* ***** *****   ** *
* *             *  *
* *******  *       *
************ *******

The code I use to read this maze:

void MazeClass::ReadMaze(ifstream& mazedata){
    mazedata >> row >> column;
    GetExit(mazedata);
    GetEntrance(mazedata);
    maze= new char*[row];
    for (unsigned i=0; i<row;i++)
    {
        maze[i]=new char[column];
    }
    /*
        maze=new char[column];
        *maze[i]=new char[column];
    */
    for (int y=0;y<column;y++)
    {//Keeping the maze inside boundries (step 1)
        for (int x=0;x<row;x++)//(Step 2)
        {
            maze[x][y]=mazedata.get();
        }
    }
}

and the code I use to display the maze is:

void MazeClass::Display(){
    cout << "Entrance is: " << entx << ' ' << enty << endl;
    cout << "Exit is: " << exitx << ' ' << exity << endl;
    cout << "Maze is: " << endl;
    for (int y=0;y<column;y++)
    {
        for (int x=0;x<row;x++)
        {
            cout << maze[x][y];
        }
        cout << endl;
    }
}

The output of which looks like:

Entrance is: 6 12
Exit is: 0 18
Maze is: 

******
*******
***** *

*     
*      
***** *

* ****
* ***  
      *

* ****
* *****
   ** *

* *   

   *  *

* ****
***  * 
      *

******
****** 

Thank you ahead of time for all the help.


Solution

    • You're not skipping EOL's (\n) when reading the maze data.
    • You're swapping x and y

    for (int y=0; y < rows; y++) // rows outer
    {
        for (int x=0;x < columns ;x++)// columns inner
        {
            maze[y][x]=mazedata.get(); // Swapped y and x
        }
        mazedata.get(); // skip \n
    }
    

    Same change's needed for Display