Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print leading zeros with C++ output operator?

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; 
like image 908
Frank Avatar asked Feb 10 '09 00:02

Frank


2 Answers

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

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

like image 131
paxdiablo Avatar answered Sep 20 '22 20:09

paxdiablo


Use the setw and setfill calls:

std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl; 
like image 23
Nik Reiman Avatar answered Sep 19 '22 20:09

Nik Reiman