IYL

导航

从txt文件中读取数据放在二维数组中

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);  // 关闭文件

 

 

posted on 2016-06-14 18:10  IYL  阅读(4980)  评论(1编辑  收藏  举报