Making of C++ Technical Documents
HTMLを書いたことのある方はご存知でしょうが、HTMLの中にはタグと呼ばれる'<'と'>'で囲まれた書式指定がたくさん含まれています。
たとえばHTMLに <B>ボールド</B> と書けば ボールドと表示されます。
今あなたが読んでいる一連の&C++ Technical Documents&には大量のC++ソースコードが書かれています。C++のソースコードには'<'や'>'でいっぱいなので、これをそのままHTMLの中に書いちゃうとタグと誤認識されてしまいます。だから、
#include <iostream>
#include <algorithm>
#include "to_string.h"
using namespace std;
void std_count() {
cout << "count, count_if" << endl;
const int N = 6;
int input[N] = { 2, 2, 4, 3, 2, 5 };
cout << to_string(input, input+N) << " 内にある、" << endl
<< " 2 の数: " << count(input, input+N, 2) << endl;
}
は、HTMLでは:
<PRE>#include <iostream>
#include <algorithm>
#include "to_string.h"
using namespace std;
void std_count() {
cout << "count, count_if" << endl;
const int N = 6;
int input[N] = { 2, 2, 4, 3, 2, 5 };
cout << to_string(input, input+N) << " 内にある、" << endl
<< " 2 の数: " << count(input, input+N, 2) << endl;
}</PRE>
と書かねばなりません。すなわち、
- '&' は '&' に、
- '"' は '"' に、
- '<' は '<' に、
- '>' は '>' に
変換するわけですね。
この変換作業を手でやっていては時間がいくらあっても足りません。
このドキュメントを書くに先立ってソースコードをHTML形式に変換するちいさなプログラムを作ることにしました。
要するに上記の変換規則に従って文字を置き換えればいいわけです。
アルゴリズムはこんな感じ:
- 変換のための辞書を作る
- 入力がなくなるまで
- 入力文字を取り出す
- 入力文字をkeyとして検索する
- 変換辞書に登録されていたら、対応するvalue(文字列)を出力する。
- 変換の必要がないなら、入力文字をそのまま出力する。
よし、それではこのアルゴリズムに忠実なコードを示しましょう。もちろんSTLをバキバキに使います^^;
#include <string>
#include <map>
using namespace std;
template
OutputIterator
src2html(InputIterator first, InputIterator last, OutputIterator result) {
map conv; // [1]
conv['&'] = "&";
conv['"'] = """;
conv['<'] = "<";
conv['<'] = ">";
while ( first != last ) { // [2]
char ch = *first++; // [2.1]
map::iterator i = conv.find(ch); // [2.2]
if ( i != conv.end() ) // [2.3]
result = copy(i->second.begin(), i->second.end(), result);
else // [2.4]
*result++ = ch;
}
return result;
}
ではこいつを使って標準入力から読み込んだソースをHTML変換して標準出力に吐き出しましょう。
int main() {
ostreambuf_iterator<char> result(cout);
string pre = "<HTML><BODY><PRE>";
copy(pre.begin(), pre.end(), result);
istreambuf_iterator<char> input(cin);
istreambuf_iterator<char> last;
src2html(input, last, result);
string post = "</PRE></BODY></HTML>";
copy(post.begin(), post.end(), result);
return 0;
}
完全なソースsrc2html.cppを自分自身に食わせでできたHTMLがこれです。
同様のWindowsアプリケーション&src2html.exe&をVisual C++ 6.0で書いてみました。

このアプリケーションはエクスプローラからのDrag&Dropに対応しています。このページももちろん、src2html.exeを使って書きました。
こいつの全ソースおよび実行形式はここにあります。