LoginSignup
1
2

More than 5 years have passed since last update.

C++11: C++コードをmarkdownに変換する

Last updated at Posted at 2013-12-27
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";
    }
}
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2