Search code examples
c++multidimensional-arrayofstream

unable to write the value of an object to a text file c++


I'm fairly new to c++ and am in need of some guidance. I currently have a 9x9 2d array made up of "cell" objects that store things such as cell value, position ect.

I can access the cell value using the method int getValue();

int cell::getValue()
{
  return value;
}

I've used this method with no problems throughout my program, however, my problem occurs when trying to stream the values of each cell to a text file.

Here's the method for streaming the values to a text file:

void SudokuPuzzle::Output() const
{
ofstream fout("sudoku_solution.txt"); // DO NOT CHANGE THE NAME OF THIS FILE
if(fout.is_open())
{
    for(int y = 0; y < 9; ++y)
    {
        for(int x = 0; x < 9; ++x)
        {
            // output each grid value followed by " "
            fout << grid[y][x].getValue() << " ";

        }

        fout << endl;
    }
    fout.close();
}
}

The error occurs on the line:

fout << grid[y][x].getValue() << " ";

'int cell::getValue(void)': cannot convert 'this' pointer from 'const cell' to 'cell &'

Edit: The grid is defined as follows:

cell grid[9][9];

please don't hesitate to ask if any more information is needed. Any help would be appreciated!


Solution

  • Its not totally clear from the code provided, but if grid is a member of SodukuPuzzle, then as the Output method is const, the grid is within the method which means grid[y][x] is const. cell::getValue is non-const and so can't be called on a const object. You can probably fix this by making cell::getValue const.