📦 归档笔记 — 原创建于 WizNote,仅作归档展示;观点以当年为准,非最新。

c++ fmt::format

创建时间2021-01-11最后修改2021-01-11原位置/程序员成长之旅/C++/库/format/字数653
目录:程序员成长之旅/C++/库/format

填充与对齐[1]

基本格式:填充与对齐(可选) 符号(可选)#(可选) 0(可选) 宽度(可选) 精度(可选) L(可选) 类型(可选)

  • < :强制域在可用空间内左对齐。这在使用非整数非浮点显示类型时为默认。
  • :强制域在可用空间内右对齐。这在使用整数或浮点显示类型时为默认。

  • ^ :强制域在可用空间中央,通过在值的前面插入n/2向下取整个字符,后面插入n/2向上取整个字符,其中 n 是待插入的总字符数。
  • 填充与对齐 是一个可选的填充字符(可为任何 { 或 } 外的的字符),后随对齐选项 < 、 > 、 ^ 之一。对齐选项的意义如下:

char c = 120; auto s0 = std::format("{:6}", 42); // value of s0 is " 42" auto s1 = std::format("{:6}", 'x'); // value of s1 is "x " auto s2 = std::format("{:*<6}", 'x'); // value of s2 is "x*****" auto s3 = std::format("{:*>6}", 'x'); // value of s3 is "****x" auto s4 = std::format("{:^6}", 'x'); // value of s4 is "x*" auto s5 = std::format("{:6d}", c); // value of s5 is " 120" auto s6 = std::format("{:6}", true); // value of s6 is "true "

char c = 120; auto s1 = std::format("{:+06d}", c); // value of s1 is "+00120" auto s2 = std::format("{:#06x}", 0xa); // value of s2 is "0x000a" auto s3 = std::format("{:<06}", -42); // value of s3 is "-42 " (0 is ignored because of < alignment)

符号 选项能为下列之一:

    • :指示符号应该一同用于非负数和负数。在非负数的输出值前插入 + 号。
    • :指示符号应该仅用于负数(这是默认行为)。
  • 空格:指示应对非负数使用前导空格,而对负数使用负号。

负零被当作负数。符号 选项应用于浮点无穷大和 NaN 。

double inf = std::numeric_limits<double> ::infinity(); double nan = std::numeric_limits<double> ::quiet_NaN(); auto s0 = std::format("{0:},{0:+},{0:-},{0: }", 1); // value of s0 is "1,+1,1, 1" auto s1 = std::format("{0:},{0:+},{0:-},{0: }", -1); // value of s1 is "-1,-1,-1,-1" auto s2 = std::format("{0:},{0:+},{0:-},{0: }", inf); // value of s2 is "inf,+inf,inf, inf" auto s3 = std::format("{0:},{0:+},{0:-},{0: }", nan); // value of s3 is "nan,+nan,nan, nan"

自定义类型的格式化:

#include <format> #include <iostream>

// A wrapper for type T template<class T> struct Box { T value; };

// The wrapper Box<T> can be formatted using the format specification of the wrapped value template<class T, class CharT> struct std::formatter<Box<T> , CharT> : std::formatter<T, CharT> { // parse() is inherited from the base class

// Define format() by calling the base class implementation with the wrapped value template<class FormatContext> auto format(Box<T> t, FormatContext& fc) { return std::formatter<T, CharT> ::format(t.value, fc); } };

int main() { Box<int> v = { 42 }; std::cout << std::format("{:#x}", v); }

参考

  1. ^参考cppref [https://en.cppreference.com/w/cpp/utility/format/formatter

来源: https://www.zhihu.com/question/421778071](https://en.cppreference.com/w/cpp/utility/format/formatter)