c++ - 用于构建 DLL 的 C++ 源文件:从文件中读取文本并将其替换为另一个文件
问题描述
我对整个 C++ 编程和学习它非常陌生。
我想构建一个 DLL,它可以读取程序 A 的文本输出,并将此文本插入模板文件的各个位置,以生成程序 B 的文件。
程序 A 的输出如下所示: FileA
1 A 23
2 B 4
3 C 5
4 D 4
5 E 2
6 A 6
7 B 7
8 C 55
9 D 66
10 E 8
11 A 2
12 B 34
13 C 55
14 D 2
15 E 1
16 1 0.45
17 2 0.45
18 3 0.10
我想阅读第 1-5、6-10、11-15 和 16-18 行并替换此模板文件中标记之间的文本:
-Start1 #marker
A 1
B 1
C 1
D 1
E 1
-End1 #marker
//some text
-Start2 #marker
A 2
B 2
C 2
D 2
E 2
-End2 #marker
//some text
-Start3 #marker
A 3
B 3
C 3
D 3
E 3
-End3 #marker
//some text
-Start4 #marker
1 1
2 2
3 3
-End4 #marker
//some text
这将为程序 B生成FileB 。
A 23
B 4
C 5
D 4
E 2
//some text
A 6
B 7
C 55
D 66
E 8
//some text
A 2
B 34
C 55
D 2
E 1
//some text
1 0.45
2 0.45
3 0.10
//some text
我的代码只能处理一个文本替换块,但我不知道如何使用一个 C++ 源文件在不同位置处理四个文本替换。
void ReadTemplate(const double inputs[], const int numArgs)
{
char buffer[500];
int i;
std::ifstream infile("input_template.txt");
std::ofstream outfile("output.txt");
while (!infile.eof())
{
infile.getline((char*)buffer, sizeof(buffer));
if (strcmp(buffer, "-Start1") == 0)
{
break;
}//Stop reading when start marker reached.
outfile << buffer << '\n'; //dump lines to outfile
}
//replace the existing text in infile with the text produced by the program:
for (i = 0; i < numArgs; i++)
{
infile.getline((char*)buffer, sizeof(buffer));
std::istrstream insert1(buffer);
infile.getline((char*)buffer, sizeof(buffer));
while (!infile.eof())
{
infile.getline((char*)buffer, sizeof(buffer));
if (strcmp(buffer, "-End1") == 0)
{
break;
}//Stop reading when start marker reached.
outfile << buffer << '\n';
}
//
// Add code for other three text replacements????
//
infile.close();
outfile.close();
return;
}
我想提供实际文件,但不知道如何提供。任何帮助将不胜感激。谢谢
解决方案
您需要创建一个状态机,以便知道如何处理每一行。该状态机有两种状态(在一个部分内或不在一个部分内)。前两种情况是两者之间的过渡,后两种情况处理非过渡线。
std::string line;
std::string current_section;
while (std::getline(infile, line)) {
if (line.find("-Start") == 0) {
// extract first word
std::istringstream(line) >> current_section;
} else if (line.find("-End") == 0) {
current_section = {};
} else if (current_section.empty()) {
outfile << line << "\n";
} else {
std::string token;
std::istringstream(line) >> token;
// TODO for you: implement lookup based on current_section and token.
outfile << token << " " << lookup(current_section, token) << "\n";
}
}
推荐阅读
- c++ - 假设没有编译器优化,这个对象会被创建多少次?
- javascript - Node.js + Apache - https://localhost:3000/socket.io/ERR_CONNECTION_REFUSED
- python - 获取 youtube 频道中所有视频的 VIDEO URL
- c# - 如何在docker中设置dotnet core的环境?
- java - 流 Java 最大值比较器
- powershell - 来自流的 PowerShell 读取行
- c# - 为什么我的 Excel 表格在打开文件时使用 OpenXml 以编程方式创建并引发错误?
- java - 使用 JSch 通过 SSH 运行多个命令的问题
- r - 试图绘制散点图但得到不同的图,这是为了预测明年这个结果背后的问题是什么?
- python - Python中的“线程”与“线程”包