Sunday, July 31, 2011

Printing Leading Zeros in C++ using setw

http://www.itguide.co.in/images/3006_C___Language_Tutorial.png.gif
setw sets the number of characters to be used as the field width for the next insertion operation.

Behaves as if a call to the stream's member ios_base::width with n as its argument was made.

The field width determines the minimum number of characters to be written in some output representations. If the standard width of the representation is shorter than the field width, the representation is padded with fill characters (see setfill) at a point determined by the format flag adjustfield (left, right or internal).

This manipulator is declared in header <iomanip>, along with the other parameterized manipulators: resetiosflags, setiosflags, setbase, setfill and setprecision. This header file declares the implementation-specific smanip type, plus any additional operator overload function needed to allow these manipulators to be inserted and extracted to/from streams with their parameters.

Here's a simple example for displaying leading zeros using setw function.


#include <iomanip>
#include <iostream>

using namespace std;

int main( )
{
   const int num_members = 6;
   const int id[num_members]    6518,3};
   const int month[num_members9111210};
   const int day[num_members]   21133031};
   const int year[num_members2000200320041998,20012003 };

   cout << setfill'0' );
   forint i = 0; i < num_members; ++i )
      cout << " : " << setw<< id[i]
           << " : " << setw<< month[i<< "/"
           << setw<< day[i<< "/" << setw)
           << year[i100 << endl;
}

  Out Put:                                
via [java2s]

0 comments:

Post a Comment