Print leading zeros with C++ output operator (printf equivalent)?

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;

Answers


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.

Use the setw and setfill calls:

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

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

from:

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


or,

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

will output 00001 as the OP already wanted to do


Need Your Help

in Javascript/jQuery, how to check a specific part of a string and determine if it is a whitespace or letter?

javascript jquery

I want to write a function where, when I click anywhere on a string (or sentence) in HTML, it will tell me if that is a letter or a whitespace. Is this even possible? For example, I click on anyw...

Update pinned PFObject in Parse Local Storage from Parse Cloud

ios xcode swift parse.com

By object.saveEventually(), I will be able to sync my data in local storage with the cloud in Parse.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.