Qbeer666 Qbeer666 - 2 months ago 22
C++ Question

C++ reading 2d array from file

I have a small problem. I am trying to read from a file, and output the read data to a 2d array in C++. I've created a .txt file and been fixing my code but could not find out what the problem is.

My code is the following:

#include <iostream>
#include <fstream>
// this is for file handleing

using namespace std;

int Sudoku[9][9];

int main()
{
ifstream fp("sudoku.txt");
// this is for reading and opening existing file sudoku.txt
for(int row = 0; row < 9; row++){
for(int column = 0; column < 9; column++){
fp >> Sudoku[row][column];
// from fp we read the characters
}
}
for(int row = 0; row < 9; row++){
for(int column = 0; column < 9; column++){
cout << Sudoku[row][column] << " ";
}
cout << endl;
}
fp.close();
return 0;


My text file looks like this:

6 4 0 0 0 0 8 0 1
5 0 0 7 0 0 0 2 0
2 7 0 4 9 0 0 0 0
0 3 6 5 1 8 0 9 0
0 0 0 3 0 2 0 0 0
0 5 0 9 6 7 1 4 0
0 0 0 0 7 4 0 8 6
0 8 0 0 0 9 0 0 2
7 0 1 0 0 0 0 5 9


My first question: In a previous version, my array was defined inside the main function. I got always trash output instead of the content of my file. I don't understand this: do I have to define the
Sudoku
array outside my main function in order not to get obviously wrong values stored in its elements, and why ?

My second question: The output of my current code is lots of zeros. I expected to find back the elements read from the file. I don't understand this either. What am I doing wrong? I've tried to search for the answer but I'm attempting to write just this part of my sudoku solver and I'm stuck.

Answer

The two problems are linked, and it's related to a problemm with the file reading:

  • in the first case you get garbage, because a local array is not initialized. As your file reading fails, the garbage remains.
  • in the second case you get 0 because a global array has static storage type, and it's zero initialized before any use of it.

Better keep variables local unless you are obliged to to otherwise. You have to check if the ifstream fp(...); could open the file or if there's a problem:

ifstream fp("sudoku.txt");
if (! fp) {
    cout << "Error, file couldn't be opened" << endl; 
    return 1; 
}    
for(int row = 0; row < 9; row++) {  // stop loops if nothing to read
   for(int column = 0; column < 9; column++){
        fp >> Sudoku[row][column];
        if ( ! fp ) {
           cout << "Error reading file for element " << row << "," << col << endl; 
           return 1; 
        }
    }
}

It may very well be that your executable is executed with another working directory that you think.