C++ reading 2d array from file -
i have small problem. trying read file, , output read data 2d array in c++. i've created .txt file , been fixing code not find out problem is.
my code following:
#include <iostream> #include <fstream> // file handleing using namespace std; int sudoku[9][9]; int main() { ifstream fp("sudoku.txt"); // reading , opening existing file sudoku.txt for(int row = 0; row < 9; row++){ for(int column = 0; column < 9; column++){ fp >> sudoku[row][column]; // fp read 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 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 previous version, array defined inside main function. got trash output instead of content of file. don't understand this: have define sudoku
array outside main function in order not wrong values stored in elements, , why ?
my second question: output of current code lots of zeros. expected find elements read file. don't understand either. doing wrong? i've tried search answer i'm attempting write part of sudoku solver , i'm stuck.
the 2 problems linked, , it's related problemm file reading:
- in first case garbage, because local array not initialized. file reading fails, garbage remains.
- in second case 0 because global array has static storage type, , it's 0 initialized before use of it.
better keep variables local unless obliged to otherwise. have check if ifstream fp(...);
open file or if there's problem:
ifstream fp("sudoku.txt"); if (! fp) { cout << "error, file couldn't opened" << endl; return 1; } for(int row = 0; row < 9; row++) { // stop loops if nothing read for(int column = 0; column < 9; column++){ fp >> sudoku[row][column]; if ( ! fp ) { cout << "error reading file element " << row << "," << col << endl; return 1; } } }
it may executable executed working directory think.
Comments
Post a Comment