.net开发:为程式码加上行号的方法详解
Abstract
若需要将程式码放进word交报告或做文件时,或许我们会想将程式码加上行号方便讲解,如同博客园显示程式码那样,我们该如何做呢?
Introduction
使用环境:Visual C++ 9.0 / Visual Studio 2008
一段C++的小程式,可以帮程式码加上行号后输出。
以下为引用的内容:
map_code_line.cpp / C++
/*
(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 <iostream>
#include <fstream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
ifstream infile("map_code_line.cpp");
ofstream outfile("map_code_line_r.cpp");
struct print_map {
void operator() (pair<int, string> p) {
cout << p.first << " " << p.second << endl;
outfile << p.first << " " << p.second << endl;
}
};
int main() {
map<int, string> 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();
}
执行结果
以下为引用的内容:
/*
(C) OOMusou 2008 http://oomusou.cnblogs.com
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 <iostream>
#include <fstream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
ifstream infile("map_code_line.cpp");
ofstream outfile("map_code_line_r.cpp");
struct print_map {
void operator() (pair<int, string> p) {
cout << p.first << " " << p.second << endl;
outfile << p.first << " " << p.second << endl;
}
};
int main() {
map<int, string> 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();
}
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;这麽漂亮的写法。
相关文章
精彩回顾!Visual Studio 2017正式版发布全纪录
两个小时的Visual Studio 2017正式版发布纪录内容还是很丰富的,这篇文章就为大家回顾了Visual Studio 2017正式版发布全过程,感兴趣的小伙伴们可以参考一下2017-03-03在 Net7.0 环境下如何使用 RestSharp 发送 Http(FromBody和FromForm)请求
这篇文章主要介绍了在 Net7.0 环境下使用 RestSharp 发送 Http(FromBody和FromForm)请求,今天,我就两个小的知识点,就是通过使用 RestSharp 访问 WebAPI,提交 FromBody 和 FromForm 两种方式的数据,还是有些区别的,本文结合实例代码介绍的非常详细,需要的朋友参考下吧2023-09-09asp.net中使用repeater和PageDataSource搭配实现分页代码
asp.net中使用repeater和PageDataSource搭配实现分页代码,需要的朋友可以参考下2013-04-04
最新评论