C++如何读取txt文件的数据并且以二位数组存到内存中

本次实验主要的目的就是读取txt的数据,在上次博文中说到如何读取txt的数据,那篇博文读了一行数据并存在了一个一维向量中,本次实现读取二维向量。直接上代码:

解释一下:代码中的40代表有40行,8064代表有8064列。

#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <iomanip>

int main()
{
    int row = 40;
    int line = 8064;
	std::vector<std::vector<double> > V;// 二位数据组
	std::vector<double> one_row;		//行向量
	std::vector<double>::iterator it;	//迭代器
	std::ifstream ifstr_data("data.txt");	//读文件
	double d;							//传值中间值	
	int row_count = 0;					//换行标记
	int line_count = 0;					//列标记
	
	for(line_count = 0;line_count < row;line_count++)
	{
		for(row_count = 0;row_count < line;row_count++)
		{
			ifstr_data >> d;
			one_row.push_back(d);//将数据压入堆栈。
		}			
		V.push_back(one_row);
	}
	ifstr_data.close();

	for(int i = 0; i < V.size();i++)
	{
		for(int j = 0; j < V[i].size();j++)
		{
			std::cout << "V[" << i << "]["<<j<<"]="<< std::setprecision(16) << V[i][j] << std::endl;
		}
	}
	return 0;
}

c++把内存中的数据写到txt文件中

    double  d;
    //str1是文件路径  
    std::ifstream ifstr_data(str); 
    std::ofstream outfile(str1);   
    for(int i = 0; i < m; ++i)
    {
        for(int j = 0; j < n;++j)
        {
            ifstr_data >> d;//把读取的数据写到内存中
            outfile << d; //把读取的数据写到txt文件中
            outfile << " ";
            V_one.push_back(d);
        }
        outfile << std::endl;
    }    
}

  • 7
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

波雅_汉库克

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值