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

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

问题描述

如何用C ++格式化输出?换句话说,相当于使用 printf 的C ++如下所示:

  printf(%05d,zipCode); 

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



您会使用以下内容吗?

  std :: cout<< 邮政编码:<< sprintf(%05d,zipCode)<< std :: endl; 


解决方案

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

  #include< iostream> 
#include< iomanip>

使用命名空间std;
cout<< setw(5)<< setfill('0')<<邮政编码<<恩德尔

// //如果您不喜欢使用命名空间std;
std :: cout<< std :: setw(5)<< std :: setfill('0')<<邮政编码<< std :: endl;

控制填充的最常见的IO操作器是:




  • std :: setw(width)设置字段的宽度。

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

  • std :: setiosflags(align)设置对齐方式,其中align是ios :: left或ios :: right。



根据您的喜好对于使用<< ,我强烈建议您查看 fmt 库。这是对我们用于格式化内容的工具包的重要补充,它比大量长度的流水管道要好得多,使您可以执行以下操作:

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

LEWG目前也将其针对C ++ 20,这意味着它将有望成为此时的语言的基本部分(或者如果不完全潜入,则几乎可以肯定以后再说)。






< sup>(a)如果您需要处理负数,可以按以下方式使用 std :: internal

  cout<<内部<< setw(5)<< setfill('0')<<邮政编码<<恩德尔

这会将填充字符放置在符号和幅度之间。 p>




(b)这(所有邮政编码都不为负)是对我的部分,但相当安全,我保证:-)


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

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

Would you just use the following?

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

解决方案

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;

The most common IO manipulators that control padding are:

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

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:

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


(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) This ("all ZIP codes are non-negative") is an assumption on my part but a reasonably safe one, I'd warrant :-)

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

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