Correctly pad negative integers with zeros with std::cout

怎甘沉沦 提交于 2019-12-04 00:26:56
std::cout << std::setw(5) << std::setfill('0') << std::internal << -5 << '\n';
//                                                     ^^^^^^^^

Output:

-0005

std::internal

Edit:

For those those that care about such things, 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!