從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);  // 關閉文件

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM