使用 C++ 输出运算符打印前导零?

Print leading zeros with C++ output operator?(使用 C++ 输出运算符打印前导零?)

本文介绍了使用 C++ 输出运算符打印前导零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I format my output in C++? In other words, what is the C++ equivalent to the use of printf like this:

printf("%05d", zipCode);

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

I know I could just use printf in C++, but I would prefer the output operator <<.

你会用下面的吗?

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

推荐答案

这可以解决问题,至少对于非负数(a) 例如邮政编码(b) 在您的问题中提到.

This will do the trick, at least for non-negative numbers(a) such as the ZIP codes(b) mentioned in your question.

#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 操纵器是:

The most common IO manipulators that control padding are:

  • std::setw(width) 设置字段的宽度.
  • std::setfill(fillchar) 设置填充字符.
  • std::setiosflags(align) 设置对齐方式,其中 align 为 ios::left 或 ios::right.
  • 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.

根据您对使用 << 的偏好,我强烈建议您查看 fmt 库(请参阅 https://github.com/fmtlib/fmt).这是对我们用于格式化内容的工具包的一个很好的补充,并且比大量长度的流管道要好得多,允许您执行以下操作:

And just on your preference for using <<, I'd strongly suggest you look into the fmt library (see https://github.com/fmtlib/fmt). 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:

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

目前 LEWG 也将其作为 C++20 的目标,这意味着它有望成为该语言的基础部分(或者几乎可以肯定以后,如果它不完全潜入的话).

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).

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

(a) If you do need to handle negative numbers, you can use std::internal as follows:

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

这会将填充字符放在符号和大小之间.

This places the fill character between the sign and the magnitude.

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

(b) This ("all ZIP codes are non-negative") is an assumption on my part but a reasonably safe one, I'd warrant :-)

这篇关于使用 C++ 输出运算符打印前导零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 C++ 输出运算符打印前导零?

基础教程推荐