用std::cout正确填充带零的负整数
Correctly pad negative integers with zeros with std::cout
我发现这个问题已经被问过了,但每个人给出的答案都是
std::cout << std::setw(5) << std::setfill('0') << value << std::endl;
这对正数来说很好,但对于-5,它会打印:
000-5
有没有一种方法可以让它打印-0005,或者强制cout始终打印至少5位数字(这将导致-00005),就像我们可以使用printf一样?
std::cout << std::setw(5) << std::setfill('0') << std::internal << -5 << 'n';
// ^^^^^^^^
输出:
-0005
std::内部
编辑:
对于那些关心这些事情的人,N3337(~c++11
),22.4.2.2.2
:
The location of any padding is determined according to Table 91.
Table 91 - Fill padding
State Location
adjustfield == ios_base::left pad after
adjustfield == ios_base::right pad before
adjustfield == internal and a
sign occurs in the representation pad after the sign
adjustfield == internal and
representation after stage 1 began
with 0x or 0X pad after x or X
otherwise pad before
在C++20中,您将能够使用std::format
来实现这一点:
std::cout << std::format("{:05}n", -5);
输出:
-0005
同时,您可以使用std::format
基于的{fmt}库。{fmt}还提供了print
函数,使其更容易、更高效(godbolt):
fmt::print("{:05}n", -5);
免责声明:我是{fmt}和C++20 std::format
的作者。
相关文章:
- std::当在256字节边界上写入整数时,流的奇怪行为
- 什么是自动 t1=std::make_tuple(case1==case2,整数)的值
- 为什么初始化 std::vector 时不能使用模板整数?
- 如何检测 std::vector::emplace_back 上的隐式转换损失整数精度
- std::带有颜色和标题的 clog 包装器无法正确打印整数
- 从 std::string 转换为 const 无符号整数
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- 我想使用 std::stoi 函数在 cpp 中将字符串转换为整数,因为我想在字符串中找到不同数字的总和(在下级酶中)
- 如何在满足常量表达式的同时将整数传递给指针,传递给 std::array<double、integer>?
- 在 2D 整数矢量上使用 std::fill
- C++ - 重复 std::getline() 作为用户整数输入?
- 将 std::error_code 与整数进行比较
- std::reduce 似乎将结果转换为整数
- 将整数附加到 std::wstring 会给出错误
- 如何使用 C++ std 计算整数集合的前导零和尾随零
- 如何将带有前导零的整数插入到 std::string 中
- 如何使用 std::multimap 将整数键映射到两个用作多维数组坐标的整数值(对于井字)?
- 将 std::sort 与指向整数变量的指针一起使用会产生意外的输出
- 如何打印包含整数和整数集的std::映射
- C++:如何使 std::unique_ptr<int> 指向一个新整数?