我有包含带随机数的20x20矩阵的文件。我读过文件中的数字,然后存储在数组中。看来我实际上并没有将数字赋给数组,因为当我打印其中一个数字时,它显示了类似“||”而不是数字,请参阅行cout <<array[0][1]
。我的完整代码如下:存储阵列后无法处理文件中的数据
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
#define length 20
int main(){
char array[length][length];
char chs;
ifstream grid;
grid.open("D:\\Example\\digit.txt", ios::in);
while (!grid.eof()){
for (int i = 0; i < 19; i++){
for (int j = 0; j < 19; j++){
grid.get(chs);
if (!grid.eof()){
array[i][j] = chs;
cout << setw(1) << array[i][j];///It display the numbers on file, there is no problem here.*/
}
}
}
}
cout <<array[0][2];//There is problem it can not display the number it display something different than numbers.
grid.close();
while (1);
}
CONSOL的输出,文件上的数字看起来像这样。 cout <<array[0][3]
不打印
我已经改变了最后一部分
cout << endl;
for (int i = 0; i < 19; i++){
for (int j = 0; j < 19; j++){
cout << array[i][j];
}
}
cout << endl;
grid.close();
输出比对文件编号不同的最后一部分的唯一
您声明20的长度变量,然后不使用它们,并使用19的魔术数字为您的读取过程..这不是问题,但这是非常糟糕的。 – UpAndAdam