操纵符(manipulator):使用操纵符可以实现格式化输出
Manipulator | Effect |
dec | 10进制表示 |
endl | 换行并清空输出流 |
fixed | 使用定点表示 |
flush | 清空输出流 |
hex | 16进制表示 |
left | 左对齐 |
oct | 8进制表示 |
right | 右对齐 |
scientific | 使用科学计数法表示 |
setfill(c) | 用字符c填充空位 |
setprecision(n) | 设置输出精度为n |
setw(n) | 设置输出宽度为n |
showpoint | 打印小数点和后面的0 |
noshowpoint | 不打印小数点后面的0 |
showpos | 正数输出前加+ |
noshowpos | 正数输出前不加+ |
skipws | 输出前跳过空格 |
noskipos | 输出前不跳空格 |
ws | 删除空格 |
使用endl的作用:回车换行
#include <iostream>
using namespace std;
int main()
{
int i=4,j=6,k=8;
char c = '1';
cout<<i<<c<<endl<<j<<c<<'\n'<<k<<c<<endl;
return 0;
}
使用进制dec、hex、oct(操纵符的作用域直到操纵符下一次改变为止,setw除外。
#include <iostream>
using namespace std;
int main()
{
int i = 91;
cout<<"i = "<<i<<" (decimal)\n";
cout<<"i = "<<oct<<i<<" (octal)\n";
cout<<"i = "<<hex<<i<<" (hexadecimal)\n";
cout<<"i = "<<dec<<i<<" (decimal)\n";
return 0;
}
使用setw:用来设置域宽
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int i;
for(i=1;i<=1000;i*=10)
cout<<setw(6)<<i<<'\n';
return 0;
}
setw作用域只持续到本次输出结束
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int i;
cout<<setw(6);
for(i=1;i<=1000;i*=10)
cout<<i<<'\n';
return 0;
}
使用setfill:当setw设置的域宽有剩余,setfill用来设置剩余位的填充字符
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int i;
cout<<setfill('*');
for(i=1;i<=1000;i*=10)
cout<<setw(6)<<i<<'\n';
return 0;
}
使用setprecision:用来设置有效数字的位数
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float a=1.05,b=10.15,c=200.87,d=2000.87,e=20000.87;
cout<<setfill('*')<<setprecision(4);
cout<<setw(10)<<a<<'\n';
cout<<setw(10)<<b<<'\n';
cout<<setw(10)<<c<<'\n';
cout<<setw(10)<<d<<'\n';
cout<<setw(10)<<e<<'\n';
return 0;
}
setprecision和fixed联用,表示设置小数点之后的位数
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float a=1.054,b=10.153,c=200.875;
cout<<fixed;
cout<<setfill('*')<<setprecision(2);
cout<<setw(10)<<a<<'\n';
cout<<setw(10)<<b<<'\n';
cout<<setw(10)<<c<<'\n';
return 0;
}
使用left和right:使输出靠输出域的左边函数还是右边函数
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float a=5,b=43,c=104;
cout<<left<<setw(10)<<"Karen"<<right<<setw(6)<<a<<'\n';
cout<<left<<setw(10)<<"Ben"<<right<<setw(6)<<b<<'\n';
cout<<left<<setw(10)<<"Patricia"<<right<<setw(6)<<c<<'\n';
return 0;
}
使用showpoint:使浮点数输出小数点之后的数据,默认长度为6个有效数字
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float a=5,b=43.3,c=10304.31;
int d=10;
cout<<showpoint;
cout<<a<<'\n';
cout<<b<<'\n';
cout<<c<<'\n';
cout<<d<<'\n';
return 0;
}
格式化输出的“魔法公式”:作用使设置输出为小数点后面两位
cout.setf(ios::fixed); | cout<<fixed; |
cout.setf(ios::showpoint); | cout<<showpoint; |
cout.precision(2); | cout<<setprecision; |