如何为程式码加上行号

2008-08-11 10:50:12.0     浏览:665     来源:中国IT实验室
关键词:  程式码     上行号     行号  

/*
(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
#include
#include
#include
#include
using namespace std;
ifstream infile("map_code_line.cpp");
ofstream outfile("map_code_line_r.cpp");
struct print_map {
void operator() (pair p) {
cout << p.first << " " << p.second << endl;
outfile << p.first << " " << p.second << endl;
}
};
int main() {
map 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 p) {
cout << p.first << " " << p.second << endl;
outfile << p.first << " " << p.second << endl;
}
};

[上一页]   [第1页]   [第2页]   [第3页]   [下一页]