将数据写入到文本中,
View Code
ofstream outAMatrix; outAMatrix.open("F:\\test\\AMatrix-.txt");
通过这两条即可实现。
如果是每隔几步要写入数据到同一文件中,
View Code
ofstream outAMatrix; outAMatrix.open("F:\\test\\AMatrix-.txt",i);
将数据不断写到AMatrix-.txt中去。
如果每隔几步将数据写入到不同文件中,
View Code
char buff[256]; sprintf(buff, "F:\\test\\vel-%d.txt", i); ofstream outAMatrix; outAMatrix.open(buff, ios::end);
完全的代码段
View Code
#include<iostream> #include<math.h> #include <iomanip> #include <fstream> using namespace std; int main() { int N=5; int M=5; double **A=new double *[N+1]; for(int k=0;k<N+1;k++) A[k]= new double [M+1]; for(int i=0;i<N+1;i++) for(int j=0;j<M+1;j++) A[i][j]=0; int NUM=20; for(int i=0;i<NUM;i++) { if(i%5==0) { //printf("%d.txt",i); char buff[256]; sprintf(buff, "F:\\test\\vel-%d.txt", i); ofstream outAMatrix; outAMatrix.open(buff, ios::end); //ofstream outAMatrix; //outAMatrix.open("F:\\test\\a-%d.txt",ios::end); //修改下 outAMatrix.seekp(std::ios::end); for(int row=0;row<(N+1);row++) { for(int col=0;col<(M+1);col++) { //Temp(row,col)=A[row][col]; outAMatrix<<setprecision(5)<<A[row][col]<<" "; } outAMatrix<<endl; } outAMatrix.close(); } } }
c语言实现代码段
View Code
#include<stdio.h> #include<string.h> int main(void) { FILE *fp; char file_name[20]; int i = 1,j=0; double a[4]; double b[4]; double c[4]; for(i=0;i<4;i++) { a[i]=0; b[i]=0; c[i]=0; } memset(file_name,0x00,sizeof(file_name));//初始化字符串=0 printf("\"\n"); for(i=0;i<20;i++) { if ( i%5==0 ) { sprintf(file_name,"D:\\a-%d.txt",i/5); if((fp=fopen(file_name,"wt+"))==NULL) { printf("Cannot open file strike any key exit!"); } fprintf(fp,"%f %f\n",a[i],b[i]); fclose(fp); } } }