setw() function in C++ with Examples
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++
#include <iomanip>
#include <ios>
#include <iostream>
using namespace std;
int main()
{
int num = 50;
cout << "Before setting the width: \n" << num << endl;
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++
#include <iostream>
using namespace std;
int main()
{
string str;
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++
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
string str( "GeeksforGeeks" );
cout << "Increasing Width:\n"
<< setw(20) << str << endl;
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
Share your thoughts in the comments
Please Login to comment...