std::format : C++
About
これまでsprintf(const char *format, ...)で行っていた文字列のフォーマットをC++で行うためのもの
code:cpp
// 変数の埋め込み
std::cout << std::format("value : {}", 2038) << std::endl
Format Specifiers
Standard Format Specifiers
cf. Standard format specification - cppreference.com
{}で囲った部分の中でFormat Specifierが使用できる
Fill and Align
"{:[FILL_CHARACTOR][SYMBOL][WIDTH]}"
table: fill_and_align_symbol
Symbol Summary Example Example-Result
< 左寄せ "{:*<10}", 2038 2038******
右寄せ "{:*>10}", 2038 ******2038
^ 中央寄せ "{:*^10}", 2038 ***2038***
注 : この場合, 自動的にType : d(10進数)が指定される
Sign, # , and 0
"{:[#][SIGN][TYPE]}"
table:#
Symbol Summary Example Example-Result
# N-Ary Prefix "{:#0<8x}", 2038 0x00002038
table: sign
Symbol Summary Example Example-Result
+ 正の値/負の値に符号を付ける "{:+d}, {:+d}", 2038, -2038 +2038, -2038
- 負の値のみに符号を付ける "{:-d}, {:-d}", 2038, -2038 2038, -2038
_(space) 正の値には空白を, 負の値には符号を付ける "{:0d}, {:0d}", 2038, -2038 2038, -2038
Type
"{:[TYPE]}"
table: type
Symbol Summary Example Example-Result
d 10進表記(省略可能) "{:d}", 2038 2038
o 8進表記 "{:#o}", 03766 03766 (2038)
x 16進表記 "{:#x}", 0x7f6 0x7f6 (2038)
X 16進表記(大文字) "{:#X}", 0x7f6 0X7F6
b 2進表記 "{:#b}", 0b11111110110 0b11111110110 (2038)
B 2進表記(大文字) "{:#B}", 0b11111110110 0B11111110110 (2038)
f 浮動小数点 "{:.4f}", 0.2038 0.2038
F fと同じ
e 指数表記
E 指数表記(大文字)
c 文字 "{:c}", 'h' h
s 文字列 "{:s}, "horizon2k38" horizon2k38
? エスケープ文字列をコピー (C++23)
p ポインタ
g 自動判定
G E(指数表記)を使用する自動判定
Width and Precision
"{[WIDTH].[PRECISION]f}"
table: precision
Symbol Summary Example Example-Result
- - "{:0.8f}", std::acos(-1.0) 3.14159265
#C++
#libc++