fmtlib 格式化 基本用法 10—— 基本语法

12 篇文章 0 订阅

fmtlib基本语法:

格式字符串包含由大括号{}包围的“替换字段”。
任何不包含在大括号中的内容都被视为文字文本,它被原封不动地复制到输出中。
如果需要在文本中包含大括号字符,则可以通过加倍来转义:{{和}}

Format String Syntax
    replacement_field ::=  "{" [arg_id] [":" (format_spec | chrono_format_spec)] "}"
    arg_id            ::=  integer | identifier
    integer           ::=  digit+
    digit             ::=  "0"..."9"
    identifier        ::=  id_start id_continue*
    id_start          ::=  "a"..."z" | "A"..."Z" | "_"
    id_continue       ::=  id_start | digit

    如果格式字符串中的数字arg_id按顺序为0、1、2、…,
    则可以省略所有arg_id(而不仅仅是一些arg_id),
    并且将自动按该顺序插入数字0、1,2、。

Format Specification Mini-Language
    format_spec ::=  [[fill]align][sign]["#"]["0"][width]["." precision]["L"][type]
    fill        ::=  <a character other than '{' or '}'>
    align       ::=  "<" | ">" | "^"
    sign        ::=  "+" | "-" | " "
    width       ::=  integer | "{" [arg_id] "}"
    precision   ::=  integer | "{" [arg_id] "}"
    type        ::=  "a" | "A" | "b" | "B" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" |
                     "o" | "p" | "s" | "x" | "X"


    填充字符可以是除“{”或“}”之外的任何Unicode代码点。
    填充字符的存在由其后面的字符发出信号,该字符必须是对齐选项之一。
    如果format_spec的第二个字符不是有效的对齐选项,则假定填充字符和对齐选项都不存在。


    alignment options:
    Option          Meaning
        '<'             Forces the field to be left-aligned within the available space (this is the default for most objects).
        '>'             Forces the field to be right-aligned within the available space (this is the default for numbers).
        '^'             Forces the field to be centered within the available space.
    请注意,除非定义了最小字段宽度,否则字段宽度将始终与填充它的数据大小相同,因此对齐选项在这种情况下没有任何意义。


     sign option:
        Option  Meaning
        '+'     indicates that a sign should be used for both nonnegative as well as negative numbers.
        '-'     indicates that a sign should be used only for negative numbers (this is the default behavior).
        space   indicates that a leading space should be used on nonnegative numbers, and a minus sign on negative numbers.
     sign选项仅对浮点和带符号整数类型有效


     “#”选项会导致转换使用“备用形式”。
     对于不同的类型,备用形式有不同的定义。此选项仅对整数和浮点类型有效。
     对于整数,当使用二进制、八进制或十六进制输出时,此选项会将前缀“0b”(“0B”)、“0”或“0x”(“0X”)分别添加到输出值。
     前缀是小写还是大写取决于类型说明符的大小写,例如,前缀“0x”用于类型“x”,“0X”用于“X”。
     对于浮点数,即使后面没有数字,替换形式也会导致转换结果始终包含小数点字符。
     通常,只有后面有数字,小数点字符才会出现在这些转换的结果中。
     此外,对于“g”和“g”转换,不会从结果中删除尾随零。


     width是定义最小字段宽度的十进制整数。如果未指定,则字段宽度将由内容决定。
     在宽度字段前面加一个零(“0”)字符可以为数字类型启用符号感知零填充。
     它强制将填充放在符号或基数(如果有的话)之后,但放在数字之前。
     这用于打印形式为“+000000120”的字段。
     此选项仅对数字类型有效,对无穷大和NaN的格式设置没有影响。


     precision是一个十进制数,
     指示用“f”和“f”格式化的浮点值的小数点后应显示的位数,
     或用“g”或“g”格式化的浮点数的小数点前后应显示的数字。
     对于非数字类型,字段指示最大字段大小,换句话说,字段内容将使用多少字符。
     整数、字符、布尔值和指针值不允许使用精度。请注意,即使指定了精度,C字符串也必须以null结尾。


     “L”选项使用当前区域设置插入适当的数字分隔符。此选项仅对数字类型有效。


     type 决定数据应该如何显示

         string:
            Type           Meaning
            's'         String format. This is the default type for strings and may be omitted.
            none        The same as 's'.
        
        character:
            Type        Meaning
            'c'         Character format. This is the default type for characters and may be omitted.
            none        The same as 'c'.

        integer:
            Type        Meaning
            'b'         Binary format. Outputs the number in base 2. Using the '#' option with this type adds the prefix "0b" to the output value.
            'B'         Binary format. Outputs the number in base 2. Using the '#' option with this type adds the prefix "0B" to the output value.
            'c'         Character format. Outputs the number as a character.
            'd'         Decimal integer. Outputs the number in base 10.
            'o'         Octal format. Outputs the number in base 8.
            'x'         Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9. Using the '#' option with this type adds the prefix "0x" to the output value.
            'X'         Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9. Using the '#' option with this type adds the prefix "0X" to the output value.
            none        The same as 'd'.
        整数表示类型也可以与字符值和布尔值一起使用。
        如果未指定表示类型,则使用文本表示形式(true或false)对布尔值进行格式化。

        floating-point:
            Type        Meaning
            'a'         Hexadecimal floating point format. Prints the number in base 16 with prefix "0x" and lower-case letters for digits above 9. Uses 'p' to indicate the exponent.
            'A'         Same as 'a' except it uses upper-case letters for the prefix, digits above 9 and to indicate the exponent.
            'e'         Exponent notation. Prints the number in scientific notation using the letter ‘e’ to indicate the exponent.
            'E'         Exponent notation. Same as 'e' except it uses an upper-case 'E' as the separator character.
            'f'         Fixed point. Displays the number as a fixed-point number.
            'F'         Fixed point. Same as 'f', but converts nan to NAN and inf to INF.
            'g'         General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.
                        A precision of 0 is treated as equivalent to a precision of 1.
            'G'         General format. Same as 'g' except switches to 'E' if the number gets too large. The representations of infinity and NaN are uppercased, too.
            none        Similar to 'g', except that the default precision is as high as needed to represent the particular value.

        pointers:
            Type        Meaning
            'p'         Pointer format. This is the default type for pointers and may be omitted.
            none        The same as 'p'.

测试代码:

#include <iostream>
#include <fmt/format.h>
using namespace std;

int main(int argc, char** argv)
{
    fmt::print("First, thou shalt count to {0}", "Test"); // References the first argument
    cout << endl;

    fmt::print("Bring me a {}", "Test");     // Implicitly references the first argument
    cout << endl;

    fmt::print("From {} to {}", "Test1", "Test2");  // Same as "From {0} to {1}"
    cout << endl;

    fmt::print("test value {0:x} {0:#x} {0:X} {0:#X}", 100 );
    cout << endl;

    fmt::print("test value {0:12} {0:012}", 100);
    cout << endl;

    string x;
    //按位置访问参数
    x = fmt::format("{0}, {1}, {2}", 'a', 'b', 'c');
    cout << x << endl;
    // Result: "a, b, c"
    x = fmt::format("{}, {}, {}", 'a', 'b', 'c');
    cout << x << endl;
    // Result: "a, b, c"
    x = fmt::format("{2}, {1}, {0}", 'a', 'b', 'c');
    cout << x << endl;
    // Result: "c, b, a"
    x = fmt::format("{0}{1}{0}", "abra", "cad");  // arguments' indices can be repeated
    cout << x << endl;
    // Result: "abracadabra"


    //对齐文本并指定宽度
    x = fmt::format("{:<30}", "left aligned");
    cout << x << endl;
    // Result: "left aligned                  "
    x = fmt::format("{:>30}", "right aligned");
    cout << x << endl;
    // Result: "                 right aligned"
    x = fmt::format("{:^30}", "centered");
    cout << x << endl;
    // Result: "           centered           "
    x = fmt::format("{:*^30}", "centered");  // use '*' as a fill char
    cout << x << endl;
    // Result: "***********centered***********"


    //动态宽度:
    x = fmt::format("{:<{}}", "left aligned", 30);
    cout << x << endl;
    // Result: "left aligned                  "


    //动态精度
    x = fmt::format("{:.{}f}", 3.14, 1);
    cout << x << endl;
    // Result: "3.1"


    //替换%+f、%-f和%f并指定一个符号
    x = fmt::format("{:+f}; {:+f}", 3.14, -3.14);  // show it always
    cout << x << endl;
    // Result: "+3.140000; -3.140000"
    x = fmt::format("{: f}; {: f}", 3.14, -3.14);  // show a space for positive numbers
    cout << x << endl;
    // Result: " 3.140000; -3.140000"
    x = fmt::format("{:-f}; {:-f}", 3.14, -3.14);  // show only the minus -- same as '{:f}; {:f}'
    cout << x << endl;
    // Result: "3.140000; -3.140000"


    //替换%x和%o并将值转换为不同的基数
    x = fmt::format("int: {0:d};  hex: {0:x};  oct: {0:o}; bin: {0:b}", 42);
    cout << x << endl;
    // Result: "int: 42;  hex: 2a;  oct: 52; bin: 101010"
    // with 0x or 0 or 0b as prefix:
    x = fmt::format("int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}", 42);
    cout << x << endl;
    // Result: "int: 42;  hex: 0x2a;  oct: 052;  bin: 0b101010"


    //带前缀的填充十六进制字节,并且始终打印两个十六进制字符
    x = fmt::format("{:#04x}", 2);
    cout << x << endl;
    // Result: "0x02"



    //填充的方框图
    fmt::print(
        "*{0:*^{2}}*\n"
        "*{1: ^{2}}*\n"
        "*{0:*^{2}}*\n", "", "Hello, world!", 20);


    return 0;
}

运行结果:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值