用std::cout正确填充带零的负整数

Correctly pad negative integers with zeros with std::cout

本文关键字:整数 std cout 填充      更新时间:2023-10-16

我发现这个问题已经被问过了,但每个人给出的答案都是

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的作者。