Open In App

setw() function in C++ with Examples

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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. The setw() stands for set width and it works for both the input and the output streams.

Syntax:

std::setw(int n);

Parameters:

  • n: It is the integer argument corresponding to which the field width is to be set.

Return Value:

  • This method does not return anything. It only acts as a stream manipulator.

Example:

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;
 
    return 0;
}


Output

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

In the above example, we have used setw() to add padding to the integer output. We can use setw() for many such cases. Some of those are stated below.

Case 1: Using setw() with cin to limit the number of characters to take from the input stream.

C++




// C++ program to demonstrate the use of setw() to take limit
// number of characters from input stream
#include <iostream>
using namespace std;
 
int main()
{
    string str;
   
    // setting string limit to 5 characters
    cin >> setw(5) >> str;
   
    cout << str;
    return 0;
}


Input:

GeeksforGeeks

Output:

Geeks

Case 2: Using setw() to set the character limit for string output.

C++




// C program to demonstrate the setw() for string output
#include <iostream>
#include <iomanip>
using namespace std;
 
int main()
{
    string str("GeeksforGeeks");
 
    // adding padding
    cout << "Increasing Width:\n"
         << setw(20) << str << endl;
 
    // reducing width
    cout << "Decreasing Width:\n" << setw(5) << str;
 
    return 0;
}


Output

Increasing Width:
       GeeksforGeeks
Decreasing Width:
GeeksforGeeks

As the above example illustrate, we can increase the width of the string output using setw() but cannot decrease the output width of the string to less than the actual characters present in it.



Last Updated : 14 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads