C++ 解析txt内容,再按指定格式存储

本文介绍了一个使用C++解析TXT文件并将内容转换为特定数据结构的方法。通过定义结构体MyStructRectType和一系列函数,如split3和AnalysisMyString,实现了从TXT文件中读取数据、解析并重新格式化输出的功能。适用于需要处理和转换TXT文件数据的场景。

C++ 解析txt内容,再按指定格式存储,我这里按原格式又转了回去。

主要目的是记录相关函数,下次用到直接copy,没啥技术含量。

 

待解析txt内容

 源代码:

//====读取txt转换string=====================================================

//r-2按指定字符切分字符串
vector<string> split3(string str, char del) //忽略“空位”(::192:168:ABC::416)->(192 168 ABC 416)
{
	stringstream ss(str);
	string tok;
	vector<string> ret;
	while (getline(ss, tok, del))
	{
		if (tok > "")
			ret.push_back(tok);
	}
	return ret;
}

struct MyStructRectType
{
	int x;
	int y;
	int w;
	int h;
	int itype;
};

//读取txt里的string
string AnalysisMyString(string file)
{
	//-------------提取string-------------------------------------------------------------------
	int irectID = 0;
	ifstream infl(file);
	string sl;
	string slay;

	vector<MyStructRectType>  iVecStruct;
	MyStructRectType mySt;

	vector<string> sVec;
	int iLine = 0;
	while (infl && !infl.eof())
	{
		iLine++;
		getline(infl, sl);
		
		if (!sl.empty() && iLine >= 4)
		{

			sVec = split3(sl, '<');
			sVec = split3(sVec[0], '>');
			sVec = split3(sVec[1], ',');

			mySt.x = std::stoi(sVec[0]);
			mySt.y = std::stoi(sVec[1]);
			mySt.w = std::stoi(sVec[2]);
			mySt.h = std::stoi(sVec[3]);
			mySt.itype = std::stoi(sVec[4]);
			iVecStruct.push_back(mySt);

			slay += sl + "\n";
		}
	}
	//-------------提取string--------------------------------------------------------------------

	//-------------转成string类型----------------------------------------------------------------
	string strResult; //结果字符串
	stringstream ssxmlResult;
	string imageName = "";
	ssxmlResult << "<ImageName>" << imageName << "</ImageName>" << "\n";

	ssxmlResult << "<LR_Column>" << 0 << "</LR_Column>" << "\n";
	ssxmlResult << "<All_Txt>" << 0 << "</All_Txt>" << "\n";

	for (int ia=0;ia<iVecStruct.size();ia++)
	{
		if (iVecStruct[ia].w != 0 && iVecStruct[ia].h != 0)
		{
			//ID信息
			irectID++;
			ssxmlResult << "<rect id=" << irectID << ">";
			ssxmlResult << iVecStruct[ia].x << "," << iVecStruct[ia].y << ","
				<< iVecStruct[ia].w << "," << iVecStruct[ia].h << "," << iVecStruct[ia].itype << "</rect>" << "\n";
		}
	}
	strResult = ssxmlResult.str();
	//-------------转成string类型----------------------------------------------------------------

	return strResult;
}

void main()
{
	string strDir = "D:\\txt\\GJB_Z+118-1999_page1.txt";                                    //读取txt主路径

	string strResult = AnalysisMyString(strDir);
	cout << strResult << endl;

	system("pause");
}

//====读取txt转换string=====================================================

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值