Home >Backend Development >C++ >What is the use of setw function in c++
setw function can set the width of the output field and accepts a positive integer parameter to specify the width. When printing data, if the data length is smaller than the field width, spaces will be inserted before/after the data (right-aligned by default); if the data length is larger than the field width, the original length will be output.
setw function
Purpose:
setw function is used to set the output Field width. It receives an integer value parameter that specifies the width of the output field.
Syntax:
<code class="cpp">std::setw(int width);</code>
Working principle:
Example:
<code class="cpp">#include <iostream> using namespace std; int main() { // 设置输出字段宽度为 10 个字符 cout << setw(10); // 输出一个字符串 cout << "Hello, world!" << endl; return 0; }<p>Output:</p> <pre class="brush:php;toolbar:false"><code> Hello, world!</code>
In this example, we set the output field width to 10 characters, so The string "Hello, world!" is printed in a right-justified field with 6 spaces inserted in front of the string.
Other uses:
The setw function can also be used with other manipulation functions (such as setfill) to customize the output format. For example, you can use the setfill function to change the characters that insert spaces.
The above is the detailed content of What is the use of setw function in c++. For more information, please follow other related articles on the PHP Chinese website!