Print leading zeros with C++ output operator?

C++FormattingNumbers

C++ Problem Overview


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;

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

Use the setw and setfill calls:

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

Solution 3 - C++

In C++20 you'll be able to do:

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

In the meantime you can use the {fmt} library, std::format is based on.

Disclaimer: I'm the author of {fmt} and C++20 std::format.

Solution 4 - C++

cout << setw(4) << setfill('0') << n << endl;

from:

http://www.fredosaurus.com/notes-cpp/io/omanipulators.html

Solution 5 - C++

or,

char t[32];
sprintf_s(t, "%05d", 1);

will output 00001 as the OP already wanted to do

Solution 6 - C++

Simple answer but it works!

ostream &operator<<(ostream &os, const Clock &c){
// format the output - if single digit, then needs to be padded with a 0
int hours = c.getHour();

// if hour is 1 digit, then pad with a 0, otherwise just print the hour
(hours < 10) ? os << '0' << hours : os << hours;

return os; // return the stream
}

I'm using a ternary operator but it can be translated into an if/else statement as follows

if(c.hour < 10){
 os << '0' << hours;
}
 else{
  os  << hours;
 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFrankView Question on Stackoverflow
Solution 1 - C++paxdiabloView Answer on Stackoverflow
Solution 2 - C++Nik ReimanView Answer on Stackoverflow
Solution 3 - C++vitautView Answer on Stackoverflow
Solution 4 - C++anthonyView Answer on Stackoverflow
Solution 5 - C++Jason NewlandView Answer on Stackoverflow
Solution 6 - C++A ParsView Answer on Stackoverflow