为了不直接以标志位的方式去处理流的状态, c++标准库提供了标准的操作符函数专门操控这些状态。
这组函数不属于任何类成员,定义在iomanip头文件中。
将它们用在提取运算符“>>”或插入运算符“<<”后面来设定输入/输出格式,即在读写对象之间插入一个修改状态的操作。
其中有些函数没有参数,所以又叫操作符。
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
char *p="12345",*q="678";
char f[4],g[4]; //最后一位为'\0'
int i=10;
cout<<p<<setw(6)<<q<<setw(4)<<p<<q<<endl;
cin>>setw(4)>>f>>g;
cout<<f<<endl<<g<<endl;
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
double f=22.0/7;
//在用浮点形式表示的输出中,setprecision(n)表示实数的有效位数
cout<<f<<endl;//默认有效位数为6
cout<<setprecision(3)<<f<<endl;//设置有效位数为3
//在用定点形式表示的输出中,setprecision(n)表示实数的小数位数
cout<<setiosflags(ios::fixed);
cout<<setprecision(8)<<f<<endl;//小数位数为8
return 0;
}