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
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
#include <iomanip>
#include <ios>
#include <iostream>
using namespace std;
int main()
{
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;
}
using namespace std;
int main()
{
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.
Limiting Input Characters using setw()
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
string str;
// setting string limit to 5 characters
cin >> setw(5) >> str;
cout << str;
return 0;
}
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
Limiting Output String Characters using setw()
#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;
}
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.