c++设置域宽
1.域宽
用于存放输出数据的宽度称为“域宽”。
浮点数的域宽包含小数点
- 如果域宽小于被打印数据的宽度,数据通常会在域内右对齐。
- 如果输出值的宽度大于域宽时,域宽是自动增长的。
- 域宽通常插在 百分号 和 转换说明符 之间
2.setw()函数
setw(int n)
是c++中在输出操作中使用的字段宽度设置,设置输出的域宽,n表示字段宽度。
只对紧接着的输出有效,紧接着的输出结束后又变回默认的域宽。
2.1头文件
头文件为#include <iomanip>
其中io代表输入输出,manip是manipulator(操纵器)的缩写
iomanip的作用:
主要是对cin,cout之类的一些操纵运算子,比如setfill,setw,setbase,setprecision等等。
它是I/O流控制头文件,就像C里面的格式化输出一样。
关于#include <iomanip>
头文件更加详细的信息可参见:
C++ 标准库之iomanip
C++标准库——iomanip
2.2setw()函数应用如下:
2.2.1 设置域宽 < 数据长度
setw()函数失效<---------------->不影响输出的数据的长度
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setw(1) << 1.234 << endl;
system("pause");
return 0;
}
输出效果:
2.2.2 设置域宽 = 数据长度
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setw(5) << 1.234 << endl;
system("pause");
return 0;
}
2.2.3 设置域宽 > 数据长度
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setw(8) << 1.234 << endl;
system("pause"); # 方便在调试的时候观察
return 0;
}
可以看出,输出的数据前面多了3个空格,因为设置的域宽是8,数据实际长度是5,由于默认是右对齐,所以前面使用3个空格补齐。
为了方便观察,使用占位符setfill(‘x’)函数。
本例中使用 * 进行填充:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setw(8) << setfill('*') << 1.234 << endl;
system("pause");
return 0;
}
效果如下:
2.2.4 setiosflags(ios::left)来实现输出左对齐
setw()默认的是输出右对齐,而当你想要左对齐时,便需要另外添加setiosflags(ios::left)来实现输出左对齐(这次多添加一些占位符):
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setw(18) <<
std::setiosflags(std::ios::left) << std::setfill('*') <<
1.234 << std::endl;
system("pause");
return 0;
}
效果如下: