Printing out leading 0's (or any other charachters)

This is a simple example to print out leading zeroes or any charachters when printing out numbers. The main manipulator function needed is the set field width that will set the width of the field.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This example shows how to print leading 0's in the output

#include<iostream>
#include<iomanip>

using namespace
std;

int
main()
{

int
number = 123;

cout<< "number = "<< number << endl;

cout<< "number = "<< setw(2) << setfill('0') << number << endl;
cout<< "number = "<< setw(3) << setfill('0') << number << endl;
cout<< "number = "<< setw(4) << setfill('0') << number << endl;
cout<< "number = "<< setw(5) << setfill('0') << number << endl;
cout<< "number = "<< setw(10) << setfill('0') << number << endl;

cout<< endl;
cout<< "number = "<< setw(5) << setfill('x') << number << endl;

cout<< endl;
number = 0;
cout<< "number = "<< setw(5) << setfill('x') << number << endl;

return
0;
}







The output is as follows:

Check out this stream