VC导入导出二维数组到 .txt
一. 二維數(shù)組寫(xiě)入
單純表格全是數(shù)據(jù),可以存放為 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????? //假定一行長(zhǎng)度不超過(guò) 2048 字節(jié)?
// 測(cè)定一行有幾列
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");?? //打開(kāi)文件?
? if ( fgets(buff,buff_size,fin) !=NULL)
??? row=1; //讀第一行
??col = get_col(buff);??? // 測(cè)出幾列
??while ( fgets(buff,buff_size,fin) !=NULL)
??? row++;?? // 測(cè)行數(shù)
? printf("row=%d col=%d\n",row,col);
? rewind(fin);?
?// 動(dòng)態(tài)分配 2 維數(shù)組
? 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]);?? // 你可以 分別賦值到若干一維數(shù)組。
}??
?
二. 二維數(shù)組導(dǎo)出
?例:數(shù)組 YK 是一個(gè) N*3 的二維數(shù)組?
寫(xiě)入 txt 中的格式要求每行為 YK 中的每一緯的三個(gè)數(shù)據(jù),以逗號(hào)隔開(kāi)。?
例如 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?
寫(xiě)入到 txt 中的格式要求為 0.0,0.1,0.2 1.0,1.1,1.2??
依次類(lèi)推???
#include <iostream>
#include <fstream>
#define N 2? //數(shù)據(jù)的行數(shù)?
using std::ofstream;
using std::endl;
int main(void)
{
? double YK[N][3];?
? ofstream ofs("c:\\a.txt");?? //將數(shù)據(jù)寫(xiě)入 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++)
?{????? //寫(xiě)入數(shù)據(jù)??
??? for (int j=0; j<3; j++)
?????? {??? ofs<<YK[i][j];???
???????????? if (j<2) ofs<<",";??
??????? }??
????? ofs<<endl;?
?}?
?ofs.close();???????????? //關(guān)閉文件?
?return 0;
}
總結(jié)
以上是生活随笔為你收集整理的VC导入导出二维数组到 .txt的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c语言课设宿舍管理程序,C语言程序课程设
- 下一篇: access mysql oracle数