Skip to content
Related Articles

Related Articles

Improve Article

iomanip setw() function in C++ with Examples

  • Last Updated : 29 Jul, 2021

The setw() method of iomanip library in C++ is used to set the ios library field width based on the width specified as the parameter to this method.

Syntax: 

setw(int n)

Parameters: This method accepts n as a parameter which is the integer argument corresponding to which the field width is to be set.
Return Value: This method does not returns anything. It only acts as stream manipulators.

Example 1: 

C++




// C++ code to demonstrate
// the working of setw() function
 
#include <iomanip>
#include <ios>
#include <iostream>
 
using namespace std;
 
int main()
{
 
    // Initializing the integer
    int num = 50;
 
    cout << "Before setting the width: \n"
         << num << endl;
 
    // Using setw()
    cout << "Setting the width"
         << " using setw to 5: \n"
         << setw(5);
 
    cout << num << endl;
 
    return 0;
}
Output: 



Before setting the width: 
50
Setting the width using setw to 5: 
   50

 

Example 2:

C++




// C++ code to demonstrate
// the working of setw() function
 
#include <iomanip>
#include <ios>
#include <iostream>
 
using namespace std;
 
int main()
{
 
    // Initializing the integer
    int num = 50;
 
    cout << "Before setting the width: \n"
         << num << endl;
 
    // Using setw()
    cout << "Setting the width"
         << " using setw to 10: \n"
         << setw(10);
 
    cout << num << endl;
 
    return 0;
}
Output: 
Before setting the width: 
50
Setting the width using setw to 10: 
        50

 

Reference: http://www.cplusplus.com/reference/iomanip/setw/
 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :