Open In App

How to use the setw Manipulator in C++?

Last Updated : 17 May, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

In C++, the std::setw manipulator, which stands for “set width”, is a function provided by the <iomanip> library. The width of the field in which the output of the subsequent value will be shown can be adjusted using the setw() manipulator. In this article, we will learn how we can use the setw manipulator in C++.

Example:

Input: 
num = 50;

Output: 
        50  //field width set to 10

C++ setw Manipulator

In C++, the setw() manipulator is mainly used to set the width of the next input-output operation according to the number passed to this function as argument. It ensures formatting consistency by padding the output with spaces to fit the set width.

Syntax of setw

setw(int n);

Here, n is an integer value upto which the field width is to be set.

C++ Program to Show How to Use setw Manipulator

The below example demonstrates the use of setw() function for setting the width for output value in C++.

C++
// C++ program to show how to use setw() manipulator

#include <iomanip>
#include <iostream>
using namespace std;

int main()
{

    // Initialize an integer variable.
    int num = 50;

    // Print the integer before setting the width.
    cout << "Before setting the width:" << endl
         << num << endl;

    // Set fill character to '-'.
    cout << setfill('-');

    // Setting the width using setw to 10 and printing the
    // integer.
    cout << "Setting the width using setw to 10:" << endl
         << setw(10);
    cout << num;
    return 0;
}

Output
Before setting the width:
50
Setting the width using setw to 10:
--------50

Time Complexity: O(1)
Auxilliary Space: O(1)

Explanation: In the above example the setw() is used to increase the width of the output and the setfill() manipulator fills the empty character with the given char('-') argument.


Practice Tags :

Similar Reads