C++ iomanip::setw()














































C++ iomanip::setw()



DESCRIPTION:

It is a part of the <iomanip> header which consists of functions that are used to manipulate the output of C++ program. Setw() function is used to set the field width i.e. it sets the number of characters to be used as the field width for the next insertion operation. It can be inserted or extracted on both- input or output streams.


Note:


1. Default width of setw() is 0.


2. We must insert setw() function before each element whose width we want to specify because it sets the width only for the next element in the stream.


3. If the width of the output is greater than the argument's value(value of n) then, the output width will be equal to the output size i.e the output will not get truncated as the argument given to setw() is the minimum width of the output.



Syntax:-

setw(int n);

Here n is the argument denoting the number of characters to be used as the field width.


Return:- It is a stream manipulator and hence does not return anything.

 

Program:-


#include<iostream>
#include<
iomanip>

using namespace std;

int main()

{

    // Initialising the integer

    int i = 100;


    cout<< "Before setting the width: \n" << i << endl;


    cout<< "After setting width using setw() to 10: \n" << setw(10);


cout<< i << endl;


    cout<<endl;

    cout<< setw(12);


cout<< "Amisha" << endl;

cout<<endl;

string s= "Hello cppsecrets";

cout << setw(5) << s << endl;


    return 0;


}

Output :-


Before setting the width:

100

After setting width using setw() to 10:

100

Amisha

Hello cppsecrets (for explanation- refer note 3)



Explanation:


Here in the above example of string- Amisha :-


12 fields are there

These 6 fields will remain blank


Since length of string- Amisha is 6 and we have set the field width to 12 so first 6 fields will be empty and remaining 6 will contain the string.



Comments