有时候需要把一些信息写到固定格式的代码,可以考虑把信息按行存到文件中,再使用string format,批量生成这些代码.下边是一个例子
#include <fstream>
#include <string>
#include <vector>
#include "zupply.hpp"
using namespace std;
int main()
{
//按行读信息,并保存到vector
fstream newfile, outfile;
vector<string> vec_buf;
newfile.open("F:\\work\\vs_test\\1.txt", ios::in);
if (newfile.is_open())
{
string tp;
while (getline(newfile, tp))
{
cout << tp << "\n";
vec_buf.push_back(tp);
}
newfile.close();
}
//format 并打印到文件
outfile.open("F:\\work\\vs_test\\2.txt", ios::out);
if (outfile.is_open())
{
for (auto &value : vec_buf)
{
string buf = "\
pElement = pRoot->FirstChildElement(\"{}\");\n\
if (pElement != nullptr)\n\
{\n\
const char* text = pElement->GetText();\n\
if (text != nullptr)\n\
{\n\
string location(text);\n\
m_Person.{} = location;\n\
}\n\
};\n\n";
zz::fmt::format_string(buf, value, value);
cout << buf << "\n";
outfile << buf;
}
}
return 0;
}
代码中的zupply.h是github中的一个开源代码,我放到了我的下载资源中,点这里下载.