cpp2md.cpp
/*
C/C++ コードから Qiita markdown に変換する。
*/
#if 0
行頭にある"/*" 直後の行から
行頭にある"*/" 直前の行までが文、
それ以外はコードと見做し ```cpp と ``` で囲む。
#endif
#include <iostream>
#include <string>
using namespace std;
/*
したがってこのコメントはドキュメント扱い
*/
int main() {
bool code = false;
bool doc = false;
auto starts_with = [](const string& target, const string& pattern) {
return target.length() >= pattern.length() &&
target.substr(0,pattern.length()) == pattern;
};
string line;
while (getline(cin, line)) {
// コメントの先頭
if ( starts_with(line, "/*") ) {
if ( !doc ) {
doc = true;
if ( code ) {
code = false;
cout << "```\n\n";
}
}
// コメントの末尾
} else if ( starts_with(line, "*/") ) {
if ( doc ) {
doc = false;
}
// さもなくば
} else {
if ( !doc && !code ) {
code = true;
cout << "\n```cpp\n";
}
cout << line << endl;
}
}
/* コードで終わっていたらちゃんと閉じる
*/
if ( code ) {
cout << "```\n\n";
}
}
自分自身を食わせた(cpp2md < cpp2md.cpp > cpp2md.md
)のがコチラ。
C/C++ コードから Qiita markdown に変換する。
#if 0
行頭にある"/*" 直後の行から
行頭にある"*/" 直前の行までが文、
それ以外はコードと見做し ```cpp と ``` で囲む。
#endif
#include <iostream>
#include <string>
using namespace std;
したがってこのコメントはドキュメント扱い
int main() {
bool code = false;
bool doc = false;
auto starts_with = [](const string& target, const string& pattern) {
return target.length() >= pattern.length() &&
target.substr(0,pattern.length()) == pattern;
};
string line;
while (getline(cin, line)) {
// コメントの先頭
if ( starts_with(line, "/*") ) {
if ( !doc ) {
doc = true;
if ( code ) {
code = false;
cout << "```\n\n";
}
}
// コメントの末尾
} else if ( starts_with(line, "*/") ) {
if ( doc ) {
doc = false;
}
// さもなくば
} else {
if ( !doc && !code ) {
code = true;
cout << "\n```cpp\n";
}
cout << line << endl;
}
}
/* コードで終わっていたらちゃんと閉じる
*/
if ( code ) {
cout << "```\n\n";
}
}