Easy Tutorial
❮ Android Tutorial Download1 Android Tutorial Listview ❯

English: ## C++ Setwidth() Function

Category Programming Techniques

The C++ setwidth() function is used to set the width of a field, with the syntax format as follows:

setwidth(n)

n represents the width, indicated by a number.

When the length of the output field following it is less than n, spaces are added in front of the field. When the length of the output field is greater than n, it is output in its entirety.

The following example demonstrates the use of the setwidth() function:

Example

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    // Set the width to 4 at the beginning, the length of the following tutorialpro characters is greater than 4, so it has no effect
    cout << setw(4) << "tutorialpro" << endl;
    // Set the width to 4 in the middle, the length of the following tutorialpro characters is greater than 4, so it has no effect
    cout << "tutorialpro" << setw(4) << "tutorialpro" << endl;
    // Set the spacing to 14 at the beginning, the number of tutorialpro characters is 6, supplemented by 8 spaces in front
    cout << setw(14) << "tutorialpro" << endl;
    // Set the spacing to 14 in the middle, the number of tutorialpro characters is 6, supplemented by 8 spaces in front
    cout << "tutorialpro" << setw(14) << "tutorialpro" << endl;
    return 0;
}

The output of the above code is:

tutorialpro
tutorialprotutorialpro
        tutorialpro
tutorialpro        tutorialpro

The default content filled by setwidth() is a space, which can be combined with setfill() to set other characters for filling.

Example

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    cout << setfill('*')  << setw(14) << "tutorialpro" << endl;
    return 0;
}

The output of the above code is:

********tutorialpro

** Click to Share Notes

Cancel

-

-

-

❮ Android Tutorial Download1 Android Tutorial Listview ❯