使用std::cout正确地在负整数前填充零

14

我发现这个问题已经被问过了,但是大家给出的答案都是一样的

std::cout << std::setw(5) << std::setfill('0') << value << std::endl;

这对于正数来说还好,但对于-5,它会输出:

000-5

有没有办法使其输出-0005,或者强制cout始终打印至少5个数字(这将导致-00005),就像我们可以使用printf一样?

2个回答

19
std::cout << std::setw(5) << std::setfill('0') << std::internal << -5 << '\n';
//                                                     ^^^^^^^^

输出:

-0005

std::internal

编辑:

对于那些关心这些事情的人,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

非常感谢!这个问题很快就解决了。希望这也能帮助其他人。 - BoBTFish

2
在C++20中,您将能够使用{{link1:std::format}}来完成此操作:
std::cout << std::format("{:05}\n", -5);  

输出:

-0005

与此同时,您可以使用 the {fmt} library,其中包含基于其构建的std::format. {fmt}还提供了print函数,可以使此过程更轻松高效(godbolt):
fmt::print("{:05}\n", -5); 

免责声明:我是 {fmt} 和 C++20 std::format 的作者。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接