C++ 从文件中读取二维数组

C++ reading 2d array from file

我有个小问题。我正在尝试从文件中读取数据,并将读取的数据输出到 C++ 中的二维数组。我创建了一个 .txt 文件并修复了我的代码,但无法找出问题所在。

我的代码如下:

#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;

我的文本文件如下所示:

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

我的第一个问题:在之前的版本中,我的数组是在main函数中定义的。我总是得到垃圾输出而不是我的文件内容。我不明白这一点:我是否必须在 main 函数之外定义 Sudoku 数组,以免在其元素中存储明显错误的值,为什么?

我的第二个问题:我当前代码的输出是很多零。我希望找到从文件中读取的元素。我也不明白这个。我究竟做错了什么?我试图寻找答案,但我试图只写我的数独求解器的这一部分,但我被卡住了。

这两个问题是有关联的,并且与文件读取的问题有关:

  • 在第一种情况下你会得到垃圾,因为本地数组没有被初始化。由于您的文件读取失败,垃圾仍然存在。
  • 在第二种情况下,您得到 0,因为全局数组具有静态存储类型,并且在使用它之前已将其初始化为零。

最好将变量保留在本地,除非您不得不这样做。您必须检查 ifstream fp(...); 是否可以打开文件或者是否存在问题:

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; 
        }
    }
}

很可能您的可执行文件是在您认为的另一个工作目录下执行的。