75

如何在 C++ 中格式化我的输出?换句话说,什么是 C++ 相当于使用printf这样的:

printf("%05d", zipCode);

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

你会使用以下内容吗?

std::cout << "ZIP code: " << sprintf("%05d", zipCode) << std::endl;
4

5 回答 5

107

这可以解决问题,至少对于非负数(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)设置对齐方式,其中 align 是 ios::left 或 ios::right。

只是根据您对 using 的偏好<<,我强烈建议您查看该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)这(“所有邮政编码都是非负数”)是我的一个假设,但一个相当安全的假设,我保证:-)

于 2009-02-10T00:02:59.857 回答
14

使用setw 和 setfill调用:

std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;
于 2009-02-10T00:02:50.107 回答
6

在 C++20 中,您将能够:

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

同时你可以使用基于的 {fmt}std::format

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

于 2020-06-25T16:17:15.787 回答
4
cout << setw(4) << setfill('0') << n << endl;

从:

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

于 2009-02-10T00:03:27.000 回答
1

或者,

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

将输出 00001 作为 OP 已经想做的

于 2013-08-13T11:42:29.837 回答