C++读取文本文件(Data.txt)中的数据并将其保存到二维数组中

一、Data.txt文件中的数据如下:共10行5列

0.008271420578124 0.854456431002006 0.801336578213911 0.419298139388035 0.859910080056673
0.148168165589323 0.001311301626219 0.899023038629473 0.860791205415533 0.962935554995730
0.064627833695089 0.029441506170233 0.0255747659323621 0.0620102170650206 0.523726740175469
0.072607254432586 0.685725225197179 0.804547946178628 0.197726524905090 0.886575426204672
0.410608384821223 0.499829831376401 0.773826450025988 0.568446459864227 0.914090094402607
0.225499698347063 0.837638652722978 0.782805445686074 0.043700613175250 0.440506598490008
0.259662540391377 0.525095797545405 0.176272736957892 0.772788773282351 0.520828362179958
0.819841514895154 0.022285897289309 0.472982706397996 0.948541391571323 0.387717594538515
0.182077128928792 0.988884284105640 0.750449083437161 0.758749749401662 0.171100796854719
0.214925534678133 0.455359520566324 0.527192455676292 0.115789713868215 0.873561799555105

二、C++读取“Data.txt”中的数据,保存到二维数组a中

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
#define row 10 //待读取文本文件中数据的行数
#define col 5 //待读取文本文件中数据的列数
void ReadTxtData(string filename ,double a[row][col]) {
	//filename为读取文件的地址;
	//a为一个二维数组,将文本文件里面的内容读取到数组a中
	ifstream readfile(filename);//打开文件夹
	double* ptr = &a[0][0];
	while (!readfile.eof())
	{
		readfile >> *ptr;//依次将数据读取
		ptr++;
	}
	readfile.close();//关闭文件夹
}
int main() {
	string filename = "F://Data.txt";//文件名
	double a[row][col] = {0.0};//用于将文本文件中的数据读取到二维数组a中
	ReadTxtData(filename,a);//调用函数
	//将结果显示
	for (int i = 0; i < row; i++) {
		for (int j = 0; j < col; j++) {
			cout<< a[i][j]<<" ";
		}
		cout << endl;
	}
	return(0);
}

亲测有效
运行结果:

在这里插入图片描述

  • 1
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值