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=====================================================
