×
嵌入式开发 > 详情

如何为程序代码加上行号

发布时间:2020-06-29 发布时间:
|

若需要将程序代码放进词交报告或做文件时,或许我们会想将程序代码加上行号方便讲解,如同博客园显示程序代码那样,我们该如何做呢?

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

一段C++的小程序,可以帮程序代码加上行号后输出。

map_code_line.cpp/C++


1/*
2 (c) OOMusou 2008年
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空操作员() (pairint, string> p) {
22 cout p.first ““ p.second endl;
23 outfile p.first ““ p.second endl;
24}
25};
26
27 int扼要() {
28 mapint, 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年
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 空操作员() (pairint, string> p) {
22 cout p.first ““ p.second endl;
23 outfile p.first ““ p.second endl;
24 }
25};
26
27 int扼要() {
28 mapint, 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 {
空操作员() (pairint, string> p) {
cout p.first ““ p.second endl;
outfile p.first ““ p.second endl;
}
};

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

结论
STL的地图是很好用的容器,尤其子链写法,若索引下没有元素,会自动新增,所以才会有排行[line_number++] =线; 这么漂亮的写法。



『本文转载自网络,版权归原作者所有,如有侵权请联系删除』

热门文章 更多
Digi-Key 联手 LogiSwitch 达成全球分销合作伙伴关系