操纵符(manipulator)
控制符 | 说明 | 实例 |
---|---|---|
boolalpha | 设置 bool 类型在数据流中显示为 true 或 false。默认情况下,bool 类型变量显示为1或0。 | cout << boolalpha ; 或 boolalpha (cout); |
noboolalpha | 设置 bool 类型在数据流中显示为 1 或 0 (恢复 bool 类型的显示状态至默认)。 | cout << noboolalpha ; 或 hex(noboolalpha ); |
scientific | 设置浮点数以科学计数法显示。 | cout << scientific ; 或 hex(scientific ); |
fixed | 设置浮点数以标准显示法显示。 | cout << fixed ; 或 hex(fixed ); |
hex | 设置整数类型以十六进制显示。 | cout << hex; 或 hex(cout); |
dec | 设置整数类型以十进制显示(默认情况下,整数类型是以十进制显示)。 | cout << dec; 或 dec(cout); |
cot | 设置整数类型以八进制显示 cout << oct; 或 oct(cout); | |
internal | 数值的符号位在域宽内左对齐,数值右对齐,中间由填充字符填充。 | cout << internal ; 或 oct(internal ); |
left | 设置输出数值或文本的显示形式为左对齐。 | cout << left ; 或 oct(left ); |
right | 设置输出数值或文本的显示形式为右对齐。 | cout << right ; 或 oct(right ); |
showbase | 设置数值前缀不显示 | cout << showbase ; 或 oct(showbase ); |
noshowbase | 将数值显示的形式恢复至默认状态。 | cout << noshowbase ; 或 oct(noshowbase ); |
showpoint | 即使小数部分为零,也显示浮点数的整数部分和小数点右侧的数字 | cout << showpoint ; 或 oct(showpoint ); |
noshowpoint | 仅显示数值的整数部分。 | cout << noshowpoint ; 或 oct(noshowpoint ); |
showpos | 显示正数值的 + 号。 | cout << showpos ; 或 oct(showpos ); |
noshowpos | 忽略正数值前面的 + 号。 | cout << noshowpos ; 或 oct(noshowpos ); |
skipws | 使 cin 获取输入时忽略空格。 | cout << skipws ; 或 oct(skipws ); |
noskipws | 使输入流读取空格 | cout << noskipws ; 或 oct(noskipws ); |
unitbuf | 每次执行输出操作后均会清空缓冲区。 | cout << unitbuf ; 或 oct(unitbuf ); |
nounitbuf | 将 unitbuf 复位至默认状态。 | cout << nounitbuf ; 或 oct(nounitbuf ); |
uppercase | 设置十六进制数值和科学计数法中的指数以大写形式显示。 | cout << uppercase ; 或 oct(uppercase ); |
nouppercase | 设置十六进制数字和科学计数法的指数以小写形式显示 | cout << nouppercase ; 或 oct(nouppercase ); |
flush; | 刷新缓冲区 | cout << “str” << flush; 或 flush(cout); |
endl; | 刷新缓冲区并插入一个换行符 cout << “str” << endl; | 或 endl(cout) |
例子
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main(void)
{
//cout.precision
cout << "Precision:" << cout.precision()
<< ",Value: " << sqrt(2.0) << endl;
//cout.precision(7)
cout.precision(12);
cout << "Precision:" << cout.precision()
<< ",Value: " << sqrt(2.0) << endl;
//setprecision
cout << setprecision(7);
cout << "Precision:" << cout.precision()
<< ",Value: " << sqrt(2.0) << endl;
}
输出结果
Precision:6,Value: 1.41421
Precision:12,Value: 1.41421356237
Precision:7,Value: 1.414214