C++实现Txt数组存储2

C++实现Txt数组存储2

说明

模板类实现Txt文件的读写,使用时应注意h和cpp文件放在同一目录下但cpp不要加入工程中才能使用。

程序

//CTxtT.h
#pragma once
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
#include <vector>

#include "CDebug.h"
#include "CSprintf.h"

using namespace std;
template <class T>
class CTxtT
{
public:CTxtT(string name);
	   void modifyName(string name);
	   ~CTxT() { }
	   vector<vector<T>> read();
	   bool write(vector<vector<T>> vec);
private:
	string name;
	   
};
#include "CTxtT.cpp"


//CTxtT.cpp
#include "pch.h"
#include "CTxtT.h"
template<class T>
 CTxtT<T>::CTxtT(string name)
{
	 this->name = name;
}

template<class T>
 void CTxtT<T>::modifyName(string name)
{
	 this->name = name;
}


template<class T>
 vector<vector<T>> CTxtT<T>::read()
{
	 ifstream myfile(name.c_str());
	 if (!myfile.is_open())
	 {
		 OutputDebugString(_T("can not open this file"));
		 return { };
	 }
	 int w, h;
	 myfile >> w >> h;
	 vector<vector<T>> vec;
	 vec.resize(w);
	 for (int i = 0; i < w; i++)
	 {
		 vec[i].resize(h);
	 }
	 for (int i = 0; i < w; i++)
	 {
		 for (int j = 0; j < h; j++)
		 {
			 myfile >> vec[i][j];
		 }
	 }
	 return vec;
}

template<class T>
 bool CTxtT<T>::write(vector<vector<T>> vec)
{
	 if (vec.empty())  //空的,不做任何处理
		 return false;
	 if (name.empty())
		 return false;
	 unsigned int w = vec.size();
	 unsigned int h = vec[0].size();
	 ofstream outfile(name.c_str());
	 if (!outfile.is_open())
		 return false;
	 outfile.clear();
	 outfile << w << " " << h << "\n";
	 for (unsigned int i = 0; i < w; i++)
	 {
		 for (unsigned int j = 0; j < h; j++)
		 {
			 outfile << vec[i][j];
			 if (j != h - 1)
				 outfile << " ";
		 }
		 outfile << "\n";
	 }
	 outfile.close();
	 return true;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值