Open In App

setw() function in C++ with Examples

Last Updated : 20 Feb, 2025
Comments
Improve
Suggest changes
19 Likes
Like
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

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.

Examples

The following examples demonstrate the use setw() function in C++ programs:

Setting Integer Print Width


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.

Limiting Input Characters using setw()


Input

GeeksforGeeks

Output

Geeks

Limiting Output String Characters using setw()


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.


Explore