#include <stdio.h>
//in.txt:in 2 3 4 3 4 5
//文件到矩阵中,整数时候才对为什么?小数的时候不对?
int main()
{
int *data=new int[2*3];
FILE *fp=fopen("in.txt","r");
if(!fp)
{
printf("can't open file\n");
return -1;
}
while(!feof(fp))
{
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
{
fscanf(fp,"%d", (data+i*3+j));
printf("% d",*(data+i*3+j));
}
}
printf("\n");
fclose(fp);
getchar();
return 0;
}
%%%%%%%%%%%%%%%%%%%%%下面是一个例子,读进来数据赋给结构体数组
typedef struct
{
double utcStart;
double utcEnd;
int fLeaps;
} LEAP;
int main(int argc,char* argv[])
{
FILE *fp;
fp= fopen(".\\Data\\leaps.txt","r" );//相对路径
if(!fp)
{
printf("can't open file\n");
return -1;
}
int m_LeapNums=0;
fscanf (fp,"%d",&m_LeapNums);//首先读进来数据的个数,后面定义时候要用
LEAP *m_pLeaps=new LEAP[m_LeapNums*3];
int i=0;
while(!feof(fp))
{
fscanf (fp,"%lf", &(m_pLeaps[i].utcStart));
fscanf (fp,"%lf", &(m_pLeaps[i].utcEnd));
fscanf (fp,"%d", &(m_pLeaps[i].fLeaps));
i++;
}
fclose(fp);
printf("%d", m_LeapNums);
printf("%lf\n",m_pLeaps[0].utcStart);
printf("%lf\n", m_pLeaps[1].utcEnd);
printf("%d\n",m_pLeaps[2].fLeaps);
delete []m_pLeaps ;
m_pLeaps=NULL;
getchar();
return 0;
}
数据:
24
2441317.5 2441499.5 10
2441499.5 2441683.5 11
2441683.5 2442048.5 12
2442048.5 2442413.5 13
2442413.5 2442778.5 14
2442778.5 2443144.5 15
2443144.5 2443509.5 16
2443509.5 2443874.5 17
2443874.5 2444239.5 18
2444239.5 2444786.5 19
2444786.5 2445151.5 20
2445151.5 2445516.5 21
2445516.5 2446247.5 22
2446247.5 2447134.5 23
2447134.5 2447709.5 24
2447709.5 2447925.5 25
2447925.5 2448804.5 26
2448804.5 2449169.5 27
2449169.5 2449534.5 28
2449534.5 2450083.5 29
2450083.5 2450630.5 30
2450630.5 2451179.5 31
2451179.5 2453736.5 32
2453736.5 0 33
总是会碰到一个问题:如何在不知道数据大小的时候,把文档中的数据读进来,赋给数组变量。在给数据分配内存的时候(用new)必须知道数组的大小,就必须知道要读进来的数据有多少,是这样吗?