Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
unclezhou486 authored Aug 7, 2024
1 parent aa8f033 commit 2021564
Showing 1 changed file with 26 additions and 17 deletions.
43 changes: 26 additions & 17 deletions assets/0_to_latex.cpp
Original file line number Diff line number Diff line change
@@ -1,41 +1,50 @@
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm> // 包含算法库
#include <filesystem>

namespace fs = std::filesystem;

// 仅在下划线前面添加反斜杠进行转义
std::string escape_filename(const std::string& filename) {
std::string safe_filename = filename;
size_t pos = 0;
while ((pos = safe_filename.find('_', pos)) != std::string::npos) {
safe_filename.insert(pos, "\\"); // 在下划线前面插入反斜杠
pos += 2; // 更新位置,跳过新插入的字符
}
return safe_filename;
}

int main() {
const std::string output_filename = "0output_latex_sections.tex";
const std::string output_filename = "listings.tex";
std::ofstream outfile(output_filename);

if (!outfile.is_open()) {
std::cerr << "Failed to open output file." << std::endl;
return 1;
}

outfile << "% Generated LaTeX code for C++ file listings" << std::endl;
outfile << "\\section{All}\n";
for (const auto& entry : fs::directory_iterator(".")) {
if (entry.is_regular_file() && entry.path().extension() == ".cpp") {
std::string filename = entry.path().filename().string();
std::string basename = filename.substr(0, filename.size() - 4);
if(filename=="0_to_latex.cpp") continue;
// 转换为大写
std::transform(basename.begin(), basename.end(), basename.begin(),
[](unsigned char c){ return std::toupper(c); });

std::string subsection_title = basename;
// 将文件名中的短横线替换为空白
std::replace(subsection_title.begin(), subsection_title.end(), '-', ' ');
const auto& path = entry.path();
if (entry.is_regular_file() && path.extension() == ".cpp") {
std::string filename = path.filename().string();
std::string basename = escape_filename(filename); // 转义文件名

// 构造子章节标题,这里简单地使用转义后的文件名
std::string subsection_title = basename.substr(0, basename.size() - 4);

// 输出到LaTeX文件

outfile << "\\subsection{" << subsection_title << "}\n";
outfile << "\\raggedbottom\\lstinputlisting[style=cpp]{assets/" << basename << ".cpp}\n";
outfile << "\\raggedbottom\\lstinputlisting[style=cpp]{assets/" << basename << "}\n"; // 假设.cpp文件在assets目录下
outfile << "\\hrulefill\n\n";
}
}

outfile.close();
std::cout << "LaTeX sections generated in " << output_filename << std::endl;
std::cout << "LaTeX listings generated in " << output_filename << std::endl;
return 0;
}
}

0 comments on commit 2021564

Please sign in to comment.