Home >Backend Development >C++ >How to use setw in c++
The setw() function in C is used to set the field width of the output stream and receives an integer parameter width representing the number of columns. The calling method is: std::setw(int width). It sets the field width behind the output stream, which is used to align the output. If the actual value is greater than the width, it will be truncated; if less than the width, it will be padded with spaces.
Usage of setw() function in C
setw()## in C # Function is used to set the field width of the output stream. It accepts an integer argument representing the number of columns to retain for the values being output.
Syntax:
<code class="cpp">std::setw(int width);</code>
Usage:
To use thesetw() function, you can Call it after the output stream object and specify the desired field width. The following example shows how to use it:
<code class="cpp">#include <iostream> using namespace std; int main() { cout << setw(10) << "Name" << setw(15) << "Age" << endl; cout << setw(10) << "Alice" << setw(15) << 25 << endl; cout << setw(10) << "Bob" << setw(15) << 30 << endl; return 0; }</code>
Output:
<code>Name Age Alice 25 Bob 30</code>As you can see, the example sets the width of the name and age fields so that they are within Alignment in output.
Note:
does not affect the actual value, it only affects the format of the output.
The above is the detailed content of How to use setw in c++. For more information, please follow other related articles on the PHP Chinese website!