Skip to content
Related Articles

Related Articles

iomanip setw() function in C++ with Examples
  • Last Updated : 11 Oct, 2019

The setw() method of iomaip 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++ 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++ 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/

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :