首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

C++ 為程式碼自動加上行號工具實作

     編輯:ASP.NET 基礎

在撰寫技術文件、部落格文章、程式碼審查報告時,常需要將原始碼輸出為帶行號的格式。本文提供一個極簡的 C++ 控制台程式,讀取指定原始碼檔案,自動加上行號後輸出至新檔案與螢幕,展示 STL `std::map` 與函數物件的實用技巧。

完整原始碼

/* 
   (C) OOMusou 2008
   Filename    : map_code_line.cpp
   Compiler    : Visual C++ 9.0 / Visual Studio 2008
   Description : Demo how to add line number for code
   Release     : 07/18/2008 1.0
*/
#include 
#include 
#include 
#include 
#include 

using namespace std;

ifstream infile("map_code_line.cpp");
ofstream outfile("map_code_line_r.cpp");

struct print_map 
{
    void operator() (pair p) 
    {
        cout  << p.first << " " << p.second << endl;
        outfile << p.first << " " << p.second << endl;
    }
};

int main() 
{
    map lines;
    string line;
    int line_num = 1;

    while (getline(infile, line))
        lines[line_num++] = line;

    infile.close();

    for_each(lines.begin(), lines.end(), print_map());

    outfile.close();
    return 0;
}

核心技巧解析

程式碼片段說明
map<int, string> lines;以行號為 Key、程式碼行內容為 Value 的有序容器,自動按行號排序
lines[line_num++] = line;map 的 `operator[]` 若 Key 不存在會自動插入,配合後置遞增一次完成「讀行、存入、行號+1」
for_each(lines.begin(), lines.end(), print_map());配合函數物件輸出,`map` 不支援 `std::copy` 直接輸出 pair,退而求其次用 `for_each`
struct print_map { void operator()(pair<int,string> p) {...} };函數物件封裝輸出邏輯,同時寫入螢幕與檔案

執行結果範例

 1 /*
 2 (C) OOMusou 2008 https://oomusou.cnblogs.com
 3 
 4 Filename    : map_code_line.cpp
 5 Compiler    : Visual C++ 9.0 / Visual Studio 2008
 6 Description : Demo how to add line number for code
 7 Release     : 07/18/2008 1.0
 8 */
 9 #include 
10 #include 
11 #include 
12 #include 
13 #include 
14 using namespace std;
15 ifstream infile("map_code_line.cpp");
16 ofstream outfile("map_code_line_r.cpp");
...
32     while(getline(infile, line))
33         lines[line_num++] = line;
...
37     for_each(lines.begin(), lines.end(), print_map());
...

現代化替代方案 (跨平台、更便利)

Python 一行指令

# 終端機直接執行
cat -n source.cpp > source_with_lines.cpp
# 或
nl -ba source.cpp > source_with_lines.cpp

Python 腳本 (支援輸出 HTML/Markdown)

#!/usr/bin/env python3
import sys

def add_line_numbers(input_file, output_file=None, format='text'):
    with open(input_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    if format == 'markdown':
        out = [f"{i+1:4d} | {line.rstrip()}" for i, line in enumerate(lines)]
    elif format == 'html':
        out = [f'
{i+1:4d}{line.rstrip()}
' for i, line in enumerate(lines)] else: out = [f"{i+1:4d} {line.rstrip()}" for i, line in enumerate(lines)] result = '\n'.join(out) if output_file: with open(output_file, 'w', encoding='utf-8') as f: f.write(result) else: print(result) if __name__ == '__main__': add_line_numbers(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None, 'markdown')

Visual Studio / VS Code 擴充功能

  • VS Code:Editor Line Numbers、Copy with Line Numbers (複製時自動帶行號)
  • Visual Studio:Productivity Power Tools → Copy As HTML 含行號
  • Notepad++:TextFX → TextFX Edit → Insert Line Numbers

應用場景延伸

  • 自動產生程式碼審查報告 (搭配 diff 工具)
  • 教學投影片產生器 (LaTeX `listings` / Markdown 代碼區塊)
  • 錯誤日誌自動附上原始碼行號 (需搭配 PDB/符號表)
  • 程式碼比對工具前處理 (統一行號格式再 diff)
總結: C++ STL `map` 配合 `operator[]` 自動插入特性,寫出極簡洁的行號產生器。現代開發環境建議直接善用編輯器內建功能或 Python 腳本,更靈活且支援多種輸出格式。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved