用std :: cout正确地用0填充负整数

Phi*_*ppe 12 c++ iostream cout iomanip

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

std::cout << std::setw(5) << std::setfill('0') << value << std::endl;
Run Code Online (Sandbox Code Playgroud)

这对于正数很好,但是对于-5,它会打印:

000-5
Run Code Online (Sandbox Code Playgroud)

有没有办法让它打印-0005或强制cout始终打印至少5位数(这将导致-00005),因为我们可以用printf做?

BoB*_*ish 18

std::cout << std::setw(5) << std::setfill('0') << std::internal << -5 << '\n';
//                                                     ^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

输出:

-0005
Run Code Online (Sandbox Code Playgroud)

的std ::内部

编辑:

对于那些关心这样的事情,N3337( ):~c++1122.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
Run Code Online (Sandbox Code Playgroud)