c++ fmt::format

程序员成长之旅 · 程序员成长之旅/C++/库/format · 653 字

填充与对齐[1]

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

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)