VC导入导出二维数组到 .txt

来源:互联网 发布:经济增加值算法 编辑:程序博客网 时间:2024/06/14 19:13

一. 二维数组写入

单纯表格全是数据,可以存放为 tab 分隔的 txt 文件。

例如: book1.txt

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

 
#include <stdio.h>

#define buff_size 2048      //假定一行长度不超过 2048 字节 


// 测定一行有几列

int get_col(char *buff)

{ int i,L=0,N=0;

  L = strlen(buff);

  for (i=1;i<L;i++)

      {

         if (buff[i] > 0x20 && buff[i-1] <= 0x20)

           N++;

      };

  if (buff[0] > 0x20)

       N++;

       return N;


FILE *fin;

void main()

{

  char namein[80];

  int row, col,i,j;

  char *buff;

  float **a; 
  buff = (char*)malloc(buff_size * sizeof(char));

  printf("input file name book1.txt: ");

  scanf("%s",namein);   // 取文件名

  fin = fopen(namein,"r");   //打开文件 
  if ( fgets(buff,buff_size,fin) !=NULL)

    row=1; //读第一行

  col = get_col(buff);    // 测出几列

  while ( fgets(buff,buff_size,fin) !=NULL)

    row++;   // 测行数

  printf("row=%d col=%d\n",row,col);

  rewind(fin); 


 // 动态分配 2 维数组

  a = (float **) malloc(sizeof(float *) * row);

  for (j=0;j<row;j++)

     { 

         a[j] = (float *) malloc(sizeof(float) * col);

      } 


if (!a) 

  {

     printf("no enough memory\n");

     exit(a);

  }; 
// 读入 表格

   for (j=0;j<row;j++)

      for (i=0;i<col;i++)

           fscanf(fin,"%f",&a[j][i]);

  fclose(fin); 
// 这里打印最后 1 列

  for (i=0;i<row;i++)

  printf("%f ",a[i][col-1]);   // 你可以 分别赋值到若干一维数组。

}  

 
二. 二维数组导出

 例:数组 YK 是一个 N*3 的二维数组 
写入 txt 中的格式要求每行为 YK 中的每一纬的三个数据,以逗号隔开。 
例如 N=2 YK[0][0]=0.0;YK[0][1]=0.1;YK[0][2]=0.2 YK[1][0]=1.0;YK[1][1]=1.1;YK[2][2]=2.2 
写入到 txt 中的格式要求为 0.0,0.1,0.2 1.0,1.1,1.2  
依次类推   
#include <iostream>

#include <fstream>

#define N 2  //数据的行数 


using std::ofstream;

using std::endl;

int main(void)

{
  double YK[N][3]; 

  ofstream ofs("c:\\a.txt");   //将数据写入 c:\a.txt 文件 
  YK[0][0]=0.0; 

  YK[0][1]=0.1; 

  YK[0][2]=0.2; 

  YK[1][0]=1.0; 

  YK[1][1]=1.1; 

  YK[1][2]=2.2;  
 for (int i=0; i<N; i++)

 {      //写入数据  

    for (int j=0; j<3; j++)

       {    ofs<<YK[i][j];   

             if (j<2) ofs<<",";  

        }  

      ofs<<endl; 

 } 

 ofs.close();             //关闭文件 
 return 0;

}

原创粉丝点击