1、我D盤中的test.txt文件內的內容是這樣的,也是隨機產生的二維數組
/test.txt/
5.440000 3.450000
6.610000 6.040000
8.900000 3.030000
0.140000 2.740000
8.920000 7.290000
2.580000 7.430000
1.850000 6.130000
1.350000 4.280000
... ...
2、在我的test.cpp中添加頭文件,即可使用FILE類來讀取txt文件中的數據
#include <stdio.h>
3、添加如下代碼即可
FILE *fp; // 定義一個FILE類的對象
int i,j; // 循環變量i、j
double **datain; // 定義二維數組用於存放讀取的txt數據
// 為二維數據動態分配內存
datain = new double *[DataRow];
for (i = 0; i < DataRow; i ++)
{
datain[i] = new double[DataColumn];
}
// 打開txt文件
if((fp=fopen("D:\\test.txt","r"))==NULL) // 判斷文件是否打開成功
{
printf("can not open the in file\n");
exit(0);
}
// 讀取txt文件內的數據
for(i = 0; i < DataRow; i ++)
for(j = 0; j < DataColumn; j ++)
fscanf(fp,"%lf",dataIn[i]+j); // 存入datain的第i行、第j列
fclose(fp); // 關閉文件