Search code examples
c++arraysfilestream

Need to write out grid 9x9 number text file to a new text file in the same format C++


This is the input file that my output file needs to be the same as

this is the output I currently have (its getting closer)

The first part of the problem that I have completed is to write a method that takes grid text file of 9x9 numbers into a 2d array and saves each row of the text file into each memory slot, while the other slot of the array holds the column of the numbers in each slot. here's the code to show that:

void Grid::LoadGrid(char const * const)
{
    int m_grid[9][9];     
    ifstream fp ("Grid1.txt"); 
    for (int x = 0; x < 9; x++) 
    {
        for(int y =0; y < 9; y++) 
        {
            fp >> m_grid[x][y]; 
        }
    }

    for (int x = 0; x < 9; x++) 
    {
        for (int y = 0; y < 9; y++)
        {
            cout << m_grid[x][y] << " "; 
        }
        cout << endl;

        return;
        fp.close(); 
    }       
}

That works perfectly. second problem is to now take that array and output it into a new text file what I called "GridOut.txt" heres the code for that:

     void Grid::SaveGrid(char const * const)
{
    int m_grid[9][9];
    ifstream fp("Grid1.txt");
    ofstream fout("GridOut.txt");

    for (int x = 0; x < 9; x++)
    {
        for (int y = 0; y < 9; y++)
        {
            fp >> m_grid[x][y];
            fout << m_grid[x][y];
        }
    }

    for (int x = 0; x < 9; x++)
    {
        for (int y = 0; y < 9; y++)
        {

         fout << m_grid[x][y] << " ";

        }
        fout << endl;


    }

}

This is creating a new file and putting the values in but it's not in the 9x9 grid format as it is meant to be.

Sorry for my bad English and hope it's explained well enough for people to understand.


Solution

  • fout << m_grid[x][y] << endl;
    

    This puts a newline after every number. You should replace that with a space:

    fout << m_grid[x][y] << " ";
    

    And instead of cout << endl do fout << endl.

    This is the result:

    void Grid::SaveGrid(char const* const) {
      int m_grid[9][9];
      ifstream fp("Grid1.txt");
      ofstream fout("GridOut.txt");
    
      for (int x = 0; x < 9; x++) {
        for (int y = 0; y < 9; y++) {
          fp >> m_grid[x][y];
        }
      }
    
      for (int x = 0; x < 9; x++) {
        for (int y = 0; y < 9; y++) {
          fout << m_grid[x][y] << " ";
        }
        fout << endl;
      }
    }