<分区>
我有一个小问题。我正在尝试从文件中读取数据,并将读取的数据输出到 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 函数中定义的。我总是得到垃圾输出而不是我的文件内容。我不明白这一点:我是否必须在我的主要函数之外定义 Sudoku
数组,以免在其元素中存储明显错误的值,为什么?
我的第二个问题:我当前代码的输出是很多零。我希望找到从文件中读取的元素。我也不明白这个。我究竟做错了什么?我试图寻找答案,但我试图只写我的数独求解器的这一部分,但我被卡住了。