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
}
その他の選択肢: