我正在使用 {fmt} 库 来格式化字符串和数值,但我对负整数有问题。 当我用零填充值时,无论值的符号如何,我都期望零的数量一致。
例如,使用 4 的填充,我想要以下内容:
这是一个例子:
#include <iostream>
#include "fmt/format.h"
int main()
{
std::cout << fmt::format("{:04}", -2) << std::endl;
}
将输出:
-002
有没有办法切换此行为或以不同的方式将值填零以获得我的预期结果?
感谢您的帮助,
文档中肯定没有关于 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