使用{fmt},当值为负数时,零填充的数值会更短,我可以适应这种行为吗?

问题描述 投票:0回答:1

我正在使用 {fmt} 库 来格式化字符串和数值,但我对负整数有问题。 当我用零填充值时,无论值的符号如何,我都期望零的数量一致。

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

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

这是一个例子:

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

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

将输出:

-002

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

感谢您的帮助,

c++ negative-number fmt zero-padding
1个回答
5
投票

文档中肯定没有关于 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

© www.soinside.com 2019 - 2024. All rights reserved.