In C++, how can we control the output width of cout?
In C++, the setw function from the iomanip library can be used to control output width. This function takes an integer parameter that represents the minimum width of the output. If the actual width of the output is less than the minimum width, spaces will be added before the output to make up for the difference.
Here is a sample code.
#include <iostream>
#include <iomanip>
int main() {
int num1 = 10;
int num2 = 100;
int num3 = 1000;
std::cout << std::setw(5) << num1 << std::endl;
std::cout << std::setw(5) << num2 << std::endl;
std::cout << std::setw(5) << num3 << std::endl;
return 0;
}
The output result is:
10
100
1000
In this example, the setw(5) function sets the minimum output width to 5 characters. Therefore, when the width of the output number is less than 5, spaces will be added in front.