Abstract
若需要将程式码放进word交报告或做文件时,或许我们会想将程式码加上行号方便讲解,如同博客园显示程式码那样,我们该如何做呢?
Introduction
使用环境:Visual C++ 9.0 / Visual Studio 2008
一段C++的小程式,可以帮程式码加上行号后输出。
map_code_line.cpp / C++
/*
(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();
}