使用 C++ 输出运算符打印前导零?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/530614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print leading zeros with C++ output operator?
提问by Frank
How can I format my output in C++? In other words, what is the C++ equivalent to the use of printf
like this:
如何在 C++ 中格式化我的输出?换句话说,什么是 C++ 等价于使用printf
这样的:
printf("%05d", zipCode);
I know I could just use printf
in C++, but I would prefer the output operator <<
.
我知道我只能printf
在 C++ 中使用,但我更喜欢输出操作符<<
.
Would you just use the following?
你会用下面的吗?
std::cout << "ZIP code: " << sprintf("%05d", zipCode) << std::endl;
回答by paxdiablo
This will do the trick, at least for non-negative numbers(a)such as the ZIP codes(b)mentioned in your question.
这将起到作用,至少对于非负数(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;
The most common IO manipulators that control padding are:
控制填充的最常见的 IO 操纵器是:
std::setw(width)
sets the width of the field.std::setfill(fillchar)
sets the fill character.std::setiosflags(align)
sets the alignment, where align is ios::left or ios::right.
std::setw(width)
设置字段的宽度。std::setfill(fillchar)
设置填充字符。std::setiosflags(align)
设置对齐方式,其中 align 为 ios::left 或 ios::right。
And just on your preference for using <<
, I'd strongly suggest you look into the fmt
library. This has been a great addition to our toolkit for formatting stuff and is much nicer than massively length stream pipelines, allowing you to do things like:
根据您对使用的偏好<<
,我强烈建议您查看fmt
图书馆。这是我们用于格式化东西的工具包的一个很好的补充,并且比大规模流管道要好得多,允许您执行以下操作:
cout << fmt::format("{:05d}", zipCode);
And it's currently being targeted by LEWG toward C++20 as well, meaning it will hopefully be a base part of the language at that point (or almost certainly later if it doesn't quite sneak in).
并且它目前也被 LEWG 定位为 C++20,这意味着它有望在那时成为该语言的基础部分(或者几乎可以肯定,如果它没有潜入的话)。
(a)If you doneed to handle negative numbers, you can use std::internal
as follows:
(a)如果你确实需要处理负数,你可以使用std::internal
如下:
cout << internal << setw(5) << setfill('0') << zipCode << endl;
This places the fill character betweenthe sign and the magnitude.
这会将填充字符之间的符号和幅度。
(b)This ("all ZIP codes are non-negative") is an assumption on my part but a reasonably safe one, I'd warrant :-)
(b)这(“所有邮政编码都是非负的”)是我的一个假设,但一个相当安全的假设,我保证:-)
回答by Nik Reiman
Use the setw and setfillcalls:
使用setw 和 setfill调用:
std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;
回答by anthony
cout << setw(4) << setfill('0') << n << endl;
from:
从:
回答by Jason Newland
or,
或者,
char t[32];
sprintf_s(t, "%05d", 1);
will output 00001 as the OP already wanted to do
将输出 00001,因为 OP 已经想做