views:

2337

answers:

3

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;
+2  A: 

Use the setw and setfill calls:

std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;
Nik Reiman
Re-activated and +1'ed since it shows how to do it in any namespace (also added setfill, sqook, hope you don't mind).
paxdiablo
Fair enough. "using namespace std;" is definitely evil. ;)
Nik Reiman
+12  A: 

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;

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.
paxdiablo
Note that you can also just use `cout << left` or `cout << right` for alignment.
Dan Moulding
+2  A: 
cout << setw(4) << setfill('0') << n << endl;

from:

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

anthony