Search code examples
c++ifstream

C++ suduko puzzle, initialising grid - newbie


I am currently extremely new to coding in C++, and I am trying to create a suduko solver. I am at the task now of reading in the unsolved puzzle from a text file, and sorting the numbers into the correct arrays of columns, rows and blocks.

I thought I had managed to do this for the rows and columns (still working on the blocks) however when I have stepped through my code to see if it has been working, the input value always seems to be -1. I think it maybe to do with the fact I use .get() to get the value, however I am clueless on any other way to do it.

I don't believe it is anything to with file itself because I have managed to output the contents of the file before it trys to initialise the grid. Here is my method for initialising the grid:

 void SudokuPuzzle::InitialiseGrid()
 {
ifstream sudukoIn("sudoku_puzzle.txt");
while (!sudukoIn.eof()) {
    for (int row = 0; row < 9; ++row)
    {
        for (int column = 0; column < 9; ++column)
        {
            bool g = true;
            int value = sudukoIn.get();
            if (value == 0) 
            {
                g = false;
            }
            m_gridRows[row].setCell(column, new Cell(value, g));
            m_gridColumns[column].setCell(row, new Cell(value, g));
        }
      }
     }
   }       

Another problem I am coming across is initialising the 3x3 blocks. My original idea was to use if statements, as in if row = 1,2 or 3 and column = 1,2 or 3 then make the index 1 etc. However when writing it out it seemed very unefficient and I was wondering if anyone had any better ideas??

Thank you, Lucy


Solution

  • void SudokuPuzzle::InitialiseGrid()
     {
    ifstream sudukoIn("sudoku_puzzle.txt");
    while (!sudukoIn.eof()) {
        for (int row = 0; row < 9; ++row)
        {
            for (int column = 0; column < 9; ++column)
            {
                bool g = true;
                int value;
                sudokuIn >> value;
                if (value == 0) 
                {
                    g = false;
                }
                m_gridRows[row].setCell(column, new Cell(value, g));
                m_gridColumns[column].setCell(row, new Cell(value, g));
            }
          }
         }
       }     
    

    Use the stream >> instead of .get().