使用 fmtlib,当值为负时,零填充数值更短,我可以调整这种行为吗?

jer*_*mes 5 c++ negative-number zero-padding fmt

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

将输出: -002

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

谢谢你的帮助,

par*_*omi 5

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

\n

这个问题要求 Python 具有相同的功能str.format。公认的答案是将长度移至参数,如果数字为负数,则将其增大一。将其转换为 C++:

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

分解格式语法:

\n
{0:0{1}}\n \xe2\x94\x82 \xe2\x94\x82 \xe2\x94\x94 position of the argument with the length\n \xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 "pad with zeros"\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80 position of the argument with the value\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n