日志档案

发表于 2009/11/12 20:29:00

0

标签: 无标签

如何為程式碼加上行號?

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

介绍
使用環境:Visual C++ 9.0/视觉演播室2008年

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

map_code_line.cpp/C++

1/* 
2 (c) OOMusou 2008年http://oomusou.cnblogs.com
3 
4文件名    : map_code_line.cpp
5编译器    : Visual C++ 9.0/视觉演播室2008年
6描述: 演示如何增加代码的行号
7发行     : 07/18/2008 1.0
8 *
9 #include <iostream>
10 #include <fstream>
11 #include <string>
12 #include <map>
13 #include <algorithm>
14 
15使用namespace std;
16 
17 infile的ifstream (“map_code_line.cpp”);
18 outfile的ofstream (“map_code_line_r.cpp”);
19  
20 struct print_map {
21空操作员() (pair<int, string> p) {
22     cout    << p.first << ““<< p.second << endl;
23     outfile << p.first << ““<< p.second << endl;
24}
25};
26 
27 int扼要() {
28 map<int, string>线;
29 
30线;
31 int line_num = 1;
32,当时(infile的getline (线))
33     线[line_num++] =线;
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文件名    : map_code_line.cpp
5编译器    : Visual C++ 9.0/视觉演播室2008年
6描述: 演示如何增加代码的行号
7发行     : 07/18/2008 1.0
8 *
9 #include <iostream>
10 #include <fstream>
11 #include <string>
12 #include <map>
13 #include <algorithm>
14 
15使用namespace std;
16 
17 infile的ifstream (“map_code_line.cpp”);
18 outfile的ofstream (“map_code_line_r.cpp”);
19  
20 struct print_map {
21   空操作员() (pair<int, string> p) {
22     cout    << p.first << ““<< p.second << endl;
23     outfile << p.first << ““<< p.second << endl;
24   }
25};
26 
27 int扼要() {
28   map<int, string>线;
29 
30   串线;
31   int line_num = 1;
32   当时(infile的getline (线))
33     线[line_num++] =线;
34 
35   infile.close ();
36  
37   for_each (lines.begin (), lines.end (), print_map ());
38   outfile.close ();
39}


32行

当时(infile的getline (线))
  线[line_num++] =线;


是整個程式的關鍵:使用地图,关键存放行號,价值存放每一行的程式碼。而且隨著每一行程式碼的讀入,自動增加行號。

37行

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


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

20行

struct print_map {
  空操作员() (pair<int, string> p) {
    cout    << p.first << ““<< p.second << endl;
    outfile << p.first << ““<< p.second << endl;
  }
};


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

结论
STL的地图是很好用的容器,尤其子链寫法,若索引下沒有元素,會自動新增,所以才會有排行[line_number++] =线; 這麼漂亮的寫法。

系统分类: 嵌入式系统   |   用户分类: 无分类   |   来源: 原创

    阅读(957)    回复(1)