Thursday, 16 July 2015

setw() Manipulators :


The word 'setw' stands for set width. The setw manipulator is used to display the value of an expression in specified columns. The value of expression can be string or number. If the value of expression is less than specified columns, the additional columns are left blank from left side. If output is larger than the specified columns. The use of setw has no effect on the output in this case.
  1. setw() is library function in C++.
  2. setw() is declared inside #include<iomanip>.
  3. setw() will set field width.
  4. setw() sets the number of characters to be used as the field width for the next insertion operation.

Syntax :


The syntax of 'setw' manipulator is as follows :
  
     setw(n)

The n indicates the number of columns in which the value is to be displayed.

Example 1 :

                 #include<iostream.h>
                 #include<conio.h>
                 #include<iomanip.h>          

void main(){
                
              cout<< setw (10);
              cout<< "Hello" <<endl;
getch();
}
  • Now Length of String Hello is 5.
  • We have set field width 10 so it will utilizes 5 fields.
  • Remaining 5 fields are kept blank.
  • Default Justification : Left.

Example 2 :


          #include <iostream>
          #include <iomanip>

using namespace std;

   int main(){
  
              int width = 6;
              int row;
              int column;

    for(row=1;row<=10;row++){
        for(column = 1; column <= 4; column++){
     
              cout << setw(width) << row * column;
                                              }
     cout << endl;
                            }

 return 0;
            }

Output :


 1     2     3     4
 2     4     6     8
 3     6     9    12
 4     8    12    16
 5    10    15    20
 6    12    18    24
 7    14    21    28
 8    16    24    32
 9    18    27    36
10    20    30    40

No comments:

Post a Comment