用 C + + 输出操作符打印前导零?

如何用 C + + 格式化输出?换句话说,什么是 C + + 等价于这样使用 printf:

printf("%05d", zipCode);

我知道我可以在 C + + 中使用 printf,但是我更喜欢输出操作符 <<

你能用下面这些吗?

std::cout << "ZIP code: " << sprintf("%05d", zipCode) << std::endl;
95021 次浏览

使用 Setw 和 setfill呼叫:

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

这样就可以了,至少对于非负数 (a),比如您问题中提到的邮政编码 (b)

#include <iostream>
#include <iomanip>


using namespace std;
cout << setw(5) << setfill('0') << zipCode << endl;


// or use this if you don't like 'using namespace std;'
std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;

最常见的控制填充的 IO 操纵器有:

  • std::setw(width)设置字段的宽度。
  • std::setfill(fillchar)设置填充字符。
  • std::setiosflags(align)设置对齐方式,其中的对齐方式为 ios: : left 或 ios: : right。

关于您对使用 <<的偏好,我强烈建议您查看 fmt库(参见 https://github.com/fmtlib/fmt)。这是对我们的格式化工具包的一个很好的补充,比大量长度的流管道要好得多,允许你做这样的事情:

cout << fmt::format("{:05d}", zipCode);

LEWG 目前也把 C + + 20作为目标,这意味着它有希望成为语言的基础部分(或者如果它没有悄悄进入的话,几乎可以肯定的是稍后)。


(a) 如果你的 需要处理负数,你可以使用 std::internal如下:

cout << internal << setw(5) << setfill('0') << zipCode << endl;

这将填充字符 中间的符号和大小。


(b) 这(“所有的邮政编码都是非负的”)是我的一个假设,但是一个相当安全的假设,我保证: -)

cout << setw(4) << setfill('0') << n << endl;

来自:

Http://www.fredosaurus.com/notes-cpp/io/omanipulators.html

或者,

char t[32];
sprintf_s(t, "%05d", 1);

将输出 OP 已经想要做的00001

在 C + + 20中,你可以做到:

std::cout << std::format("{:05}", zipCode);

同时你可以使用 { fmt }库std::format是基于。

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

简单的答案,但它的工作!

ostream &operator<<(ostream &os, const Clock &c){
// format the output - if single digit, then needs to be padded with a 0
int hours = c.getHour();


// if hour is 1 digit, then pad with a 0, otherwise just print the hour
(hours < 10) ? os << '0' << hours : os << hours;


return os; // return the stream
}

我使用了一个三元运算符,但是它可以转换成如下的 if/else 语句

if(c.hour < 10){
os << '0' << hours;
}
else{
os  << hours;
}