How to output default field width in cout in C++?

In C++, you can use the setw() function to set the default field width of cout. Located in the header file, setw() takes an integer parameter to set the field width. For example, the following code sets the default field width of cout to 10 characters:

#include <iostream>
#include <iomanip>

int main() {
    std::cout << std::setw(10) << "Hello" << std::endl;
    std::cout << std::setw(10) << "World" << std::endl;
    return 0;
}

Output result:

     Hello
     World

In the example above, setw(10) sets the default field width of cout to 10 characters, so the output string is filled in a field with a width of 10 characters.

bannerAds