5

我正在使用fmtlib来格式化字符串和数值,但我遇到了负整数的问题。当我用零填充该值时,无论该值的符号如何,我都希望零个数一致。

例如,使用 4 的填充,我想要以下内容:

  • 2 作为“0002”返回
  • -2 作为“-0002”返回

fmtlib 的默认行为是将前缀长度(即符号“-”)考虑到填充长度中,这意味着 -2 返回为“-002”

这是一个例子:

#include <iostream>
#include "fmt/format.h"

int main()
{
    std::cout << fmt::format("{:04}", -2) << std::endl;
}

将输出:-002

有没有办法切换这种行为或以不同的方式来零填充值以获得我的预期结果?

谢谢你的帮助,

4

1 回答 1

2

fmt 或 Python str.format(fmt 的语法基于)的文档中肯定没有任何内容。两者都只声明填充是“符号感知的”。

这个问题要求 Python 的str.format. 接受的答案是将长度移动到一个参数,如果数字为负,则将其变大。将其转换为 C++:

for (auto x : { -2, 2 }) {
    fmt::print("{0:0{1}}\n", x, x < 0 ? 5 : 4 ); // prints -0002 and 0002
}

分解格式语法:

{0:0{1}}
 │ │ └ position of the argument with the length
 │ └── "pad with zeros"
 └──── position of the argument with the value

https://godbolt.org/z/5xz7T9

于 2020-10-12T03:49:16.423 回答