当前位置:首页 > 嵌入式 > 嵌入式软件
[导读]如何为程序代码加上行号

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

介绍
使用环境: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空操作员() (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年
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++] =线; 这么漂亮的写法。

本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭