Wednesday 3 March 2010

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:

1 comment:

  1. I am sorry if my comments are irritating but here is link which has more information about C++ manipulators -
    http://www.cplusplus.com/reference/iostream/manipulators/

    Also there is mistake in my first comment - scientific is not a keyword.

    ReplyDelete