VC中如何把一个二维数组的数据写入TXT文件中

数组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

依次类推

可以使用C++的fstream类,将二维数组中的每个数据逐个写入txt文件,并每行换行。

以整型二维数组写到txt文件中为例,代码如下:

#include <fstream>
#include <iostream>
using namespace std;
int main()
{
    int a[10][10];//10*10的二维数组。
    int i,j;
    
    //输入二维数组的值。
    for(i = 0; i < 10; i ++)
    {
        for(j = 0; j < 10; j ++)
        {
            cin>>a[i][j];
        }
    }
    
    ofstream out("out.txt");//打开文件。
    for(i = 0; i < 10; i ++)
    {
        for(j = 0; j < 10; j ++)
        {
            out<<a[i][j]<<',';//将每个元素写入文件,以逗号分隔。
        }
        out << endl;//每行输出结束,添加换行。
    }
    
    return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-03-04
//---------------------------------------------------------------------------
#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;
}
//---------------------------------------------------------------------------本回答被提问者采纳
第2个回答  2010-03-04
#include <stdio.h>
#include <string.h>

#define N 2
int main()
{
int i, j;
char buffer[1024];
float YK[N][3];
FILE *fp;

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;

fp = fopen("output.txt", "wt");
if (NULL == fp)
{
printf("Error open file\n");
return 1;
}

for(i = 0; i < N; i++)
{
sprintf(buffer, "%.1f, %.1f, %.1f\n", YK[i][0], YK[i][1], YK[i][2]);
fwrite(buffer, strlen(buffer), 1, fp);
}

fclose(fp);
return 0;
}