(原創) 如何為程式碼加上行號? (C/C++) (STL)

Abstract
若需要將程式碼放進word交報告或做文件時,或許我們會想將程式碼加上行號方便講解,如同博客園顯示程式碼那樣,我們該如何做呢?

Introduction
使用環境:Visual C++ 9.0 / Visual Studio 2008

一段C++的小程式,可以幫程式碼加上行號後輸出。

map_code_line.cpp / C++

1 /* 
2 (C) OOMusou 2008 http://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 <iostream>
10 #include <fstream>
11 #include <string>
12 #include <map>
13 #include <algorithm>
14 
15 using namespace std;
16 
17 ifstream infile("map_code_line.cpp");
18 ofstream outfile("map_code_line_r.cpp");
19  
20 struct print_map {
21   void operator() (pair<int, string> p) {
22     cout    << p.first << " " << p.second << endl;
23     outfile << p.first << " " << p.second << endl;
24   }
25 };
26 
27 int main() {
28   map<int, string> lines;
29 
30   string line;
31   int line_num = 1;
32   while(getline(infile, line))
33     lines[line_num++] = line;
34 
35   infile.close();
36  
37   for_each(lines.begin(), lines.end(), print_map());
38   outfile.close();
39 }


執行結果

1 /*
2 (C) OOMusou 2008 http://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 <iostream>
10 #include <fstream>
11 #include <string>
12 #include <map>
13 #include <algorithm>
14 
15 using namespace std;
16 
17 ifstream infile("map_code_line.cpp");
18 ofstream outfile("map_code_line_r.cpp");
19  
20 struct print_map {
21   void operator() (pair<int, string> p) {
22     cout    << p.first << " " << p.second << endl;
23     outfile << p.first << " " << p.second << endl;
24   }
25 };
26 
27 int main() {
28   map<int, string> lines;
29 
30   string line;
31   int line_num = 1;
32   while(getline(infile, line))
33     lines[line_num++] = line;
34 
35   infile.close();
36  
37   for_each(lines.begin(), lines.end(), print_map());
38   outfile.close();
39 }


32行

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


是整個程式的關鍵:使用map,key存放行號,value存放每一行的程式碼。而且隨著每一行程式碼的讀入,自動增加行號。

37行

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


將map內容印出,因為map無法配合copy(),只好退而求其次使用for_each()與functor。

20行

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


配合for_each()的functor,22行的cout可以拿掉,只是方面在螢幕顯示而已。

Conclusion
STL的map是很好用的容器,尤其substring寫法,若index下沒有元素,會自動新增,所以才會有lines[line_number++] = line;這麼漂亮的寫法。

See Also
(原創) 將map輸出到cout,是否有更方便的方法? (C/C++) (STL)
(原創) 如何使用Function Object? (C/C++) (STL)
(原創) Function Pointer、Delegate和Function Object (C/C++) (template) (.NET) (C#)
(原創) 如何正確的使用迴圈(使用for_each)? (C/C++) (STL) (template)

posted on 2008-07-18 01:54  真 OO无双  阅读(3481)  评论(2编辑  收藏  举报

导航