setw()函数
setw(int n)是c++中在输出操作中使用的字段宽度设置,设置输出的域宽,n表示字段宽度。只对紧接着的输出有效,紧接着的输出结束后又变回默认的域宽。
当后面紧跟着的输出字段长度小于n的时候,在该字段前面用空格补齐;当输出字段长度大于n时,全部整体输出。
头文件
头文件为#include <iomanip>
其中io代表输入输出,manip是manipulator(操纵器)的缩写
iomanip的作用:
主要是对cin,cout之类的一些操纵运算子,比如setfill,setw,setbase,setprecision等等。它是I/O流控制头文件,就像C里面的格式化输出一样。
关于#include <iomanip> 头文件更加详细的信息可参见:
C++ 标准库之iomanip
C++标准库——iomanip
setw()函数应用如下:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setw(3) << 1 << 1234 << endl;
cout << 1234 << setw(7) << 1234 << 12345 << endl;
cout << 1234 << setw(3) << 12345 << endl;
cout << 1234 << setw(4) << 123456 << 12 << setw(5) << 123 << endl;
return 0;
}
运行结果如下,注意看空格