使用C ++输出运算符(printf等效)打印前导零? [英] Print leading zeros with C++ output operator (printf equivalent)?

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

问题描述

如何在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);

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

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

/ p>

Would you just use the following?

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


推荐答案

b
$ b

This will do the trick:

#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)设置字段的宽度。

  • code> std :: setfill(fillchar)设置填充字符。

  • std :: setiosflags code>设置对齐方式,其中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.

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

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