C++ zero padded string from int

Brian —  March 27, 2012 — Leave a comment

Using an output string stream is a handy way to convert a number to a string.

However, what if you want to zero pad the number.

Well, that’s where iomanip comes in handy.

[code language="cpp"]
#include <iomanip> // for setw, setfill
#include <iostream> // for cout
#include <sstream> // for ostringstream
#include <string> // for string

using namespace std;

int main ()
{
int i = 1;

ostringstream ss;
ss << setw( 3 ) << setfill( '0' ) << i;
string s = ss.str();

cout << "i: " << i << endl;
cout << "s: " << s << endl;
return 0;
}

[/code]

output:
[bash]
i: 1
s: 001
[/bash]

No Comments

Be the first to start the conversation.

Leave a Reply

*

Text formatting is available via select HTML. <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>