The C++ setw() function is used to set the width of a field, with the syntax format as follows:
setw(n)
n represents the width, expressed as a number.
The setw() function only affects the output that immediately follows it.When the length of the immediately following output field is less than n, spaces are added before it; when the output field length is greater than n, the entire field is output as is.
The following example demonstrates the use of the setw() function:
Example
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// Set width to 4 at the beginning; the following example string has length greater than 4, so it has no effect
cout << setw(4) << "example" << endl;
// Set width to 4 in the middle; the following example string has length greater than 4, so it has no effect
cout << "example" << setw(4) << "example" << endl;
// Set spacing to 14 at the beginning; example has 6 characters, so 8 spaces are added before it
cout << setw(14) << "example" << endl;
// Set spacing to 14 in the middle; example has 6 characters, so 8 spaces are added before it
cout << "example" << setw(14) << "example" << endl;
return 0;
}
#include <iomanip>
using namespace std;
int main()
{
// Set width to 4 at the beginning; the following example string has length greater than 4, so it has no effect
cout << setw(4) << "example" << endl;
// Set width to 4 in the middle; the following example string has length greater than 4, so it has no effect
cout << "example" << setw(4) << "example" << endl;
// Set spacing to 14 at the beginning; example has 6 characters, so 8 spaces are added before it
cout << setw(14) << "example" << endl;
// Set spacing to 14 in the middle; example has 6 characters, so 8 spaces are added before it
cout << "example" << setw(14) << "example" << endl;
return 0;
}
The output of the above code is:
example
exampleexample
example
example example
By default, setw() fills with spaces, and it can besetfill()used in combination to set other characters for filling.
Example
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setfill('*') << setw(14) << "example" << endl;
return 0;
}
#include <iomanip>
using namespace std;
int main()
{
cout << setfill('*') << setw(14) << "example" << endl;
return 0;
}
The output of the above code is:
********example