C++ 读写txt文件数据

  从一个 txt 文件中读取数据,将其存入 二维数组;

例:

  现有 行数为 200, 列数为 100 的 2个 txt 文档数据,分别为 1.txt,2.txt, 路径分别为 D://1.txt, D://2.txt;

  将其存入 A,B 数组,并分别写入 D://A.txt,D://B.txt 之中。

代码:

 

#include <iostream>
#include <fstream>
using namespace std;
int n = 200, m = 100;// 行为 200 列为100 
double a[205][105], b[205][105];
void readfile() {
	int cnt = 0;
	FILE *fp1 = fopen("D://1.txt","r");
	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= m; j++) {
			fscanf(fp1, "%lf", &a[i][j]);
			cnt++;
		}
	}
	FILE *fp2 = fopen("D://2.txt","r");
	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= m; j++) {
			fscanf(fp2, "%lf", &b[i][j]);
		}
	}
	FILE *fp3 = fopen("D://3.txt","r");
}
void creatfileA() {
	ofstream outfile ("D://A.txt",ios::in|ios::out|ios::binary);
	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= m; j++){
			outfile << a[i][j] << " ";
		}
		outfile << "\r\n";
	}
}
void creatfileB() {
	ofstream outfile ("D://B.txt",ios::in|ios::out|ios::binary);
	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= m; j++){
			outfile << b[i][j] << " ";
		}
		outfile << "\r\n";
	}
}
int main() {
	readfile();
	creatfileA();
	creatfileB();
	return 0;

}