日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > c/c++ >内容正文

c/c++

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

發(fā)布時(shí)間:2025/3/12 c/c++ 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 VC导入导出二维数组到 .txt 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一. 二維數(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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。