用带std :: cout的零正确填充负整数 [英] Correctly pad negative integers with zeros with std::cout

查看:174
本文介绍了用带std :: cout的零正确填充负整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found this question already asked, but the answer everybody gives is

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

这是对正数的罚款,但是-5,它打印:

which is fine for positive numbers, but with -5, it prints:

000-5

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

Is there a way to make it print -0005 or to force cout to always print at least 5 digits (which would result in -00005) as we can do with printf?

推荐答案

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

输出:

-0005

std :: internal

编辑:

对于那些关心这些事情的人,N3337(〜c ++ 11 ), 22.4.2.2.2

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

这篇关于用带std :: cout的零正确填充负整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆