Skip to content

Instantly share code, notes, and snippets.

@kumpeishiraishi
Created May 26, 2023 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kumpeishiraishi/3d5c1413afa2797d57ab575efebefadb to your computer and use it in GitHub Desktop.
Save kumpeishiraishi/3d5c1413afa2797d57ab575efebefadb to your computer and use it in GitHub Desktop.

C++で format する

Pythonでは文字列操作が format で簡単にできる。

print("ゼロ埋め {:05d}".format(99))
# output: ゼロ埋め 00099

print("指数表記 {:.2e}".format(3.14))
# output: 指数表記 3.14e+00

この類いのことをC++でやろうとすると、ちょっと面倒だった。

#include <iostream>
#include <sstream>
#include <iomanip>
int main()
{
    std::stringstream ss1, ss2;
    ss1 << std::setfill('0') << std::right << std::setw(5) << 99;
    ss2 << std::setprecision(2) << std::scientific << 3.14;

    std::cout << ss1.str() << std::endl;
    // output: 00099

    std::cout << ss2.str() << std::endl;
    // output: 3.14e+00
}

Boost Formatライブラリだと簡単にできる。

#include <iostream>
#include <boost/format.hpp>

int main()
{
    auto a = boost::format("Hello I am %2$03d and input number is %1$.3e");

    std::cout << a % 3.14 % 3 << std::endl;
    // output: Hello I am 003 and input number is 3.140e+00

    std::cout << (a % 3.19 % 1).str() << std::endl;
    // output: Hello I am 001 and input number is 3.190e+00

    std::cout << (a % 1.19 % 0).str() << std::endl;
    // output: Hello I am 000 and input number is 1.190e+00
}

その他の選択肢:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment