在这里介绍了 stream 流操作中常用的操纵符。其中,前面带*表示为流的默认操纵符。
适合的stream流包括:输入输出流(istream和ostream),文件流(fstream),字符串流(stringstream)等。
注意:不是所有的操作符都适用于所有stream。
boolalpha | 将true和false输出为字符串 | |
* | noboolalpha | 将true和false输出为1,0 |
showbase | 对整型值输出表示进制的前缀 | |
* | noshowbase | 不生成表示进制的前缀 |
showpoint | 对浮点值总是显示小数点 | |
* | noshowpoint | 只有当浮点值包含小数部分时才显示小数点 |
showpos | 对非负数显示+ | |
* | noshowpos | 对非负数不显示+ |
uppercase | 数值中包含字母时,使用大写字母 | |
* | nouppercase | 数值中包含字母时,使用小写字母 |
* | dec | 整型值显示为十进制 |
hex | 整型值显示为十六进制 | |
oct | 整型值显示为八进制 | |
left | 在值的左侧添加填充字符 | |
right | 在值的右侧添加填充字符 | |
internal | 在符号和值之间添加填充字符 | |
fixed | 浮点值显示为定点十进制 | |
secientific | 浮点值显示为科学计数法 | |
hexfloat | 浮点值显示为十六进制(C++11以上) | |
defaultfloat | 重置浮点数格式为十进制(C++11以上) | |
unitbuf | 每次输出操作后都刷新缓冲区 | |
* | nounitbufs | 恢复默认的缓冲区刷新方式 |
* | skipws | 输入运算符跳过空白符 |
noskipws | 输入运算符跳过空白符 | |
flush | 刷新ostream缓冲区 | |
ends | 插入空字符,然后刷新ostream缓冲区 | |
endl | 插入换行,然后刷析ostream缓冲区 |
常用用法示例:
例1:使用noskipws读入包含空白符(如空格,制表符,换行符)的文本。
#include<iostream> using namespace std; int main(){ char c; while(cin>>c) cout<<c; return 0; }
#include<iostream> using namespace std; int main(){ char c; cin>>noskipws; while(cin>>c) cout<<c; return 0; }
对于两段程序,我们给定同样的输入
a b c d
程序1输出忽略了所有的空格和制表符:
abcd
程序2原样输出:
a b c d
例2:常用的浮点数相关操纵符示例。
#include<iostream> #include<math.h> using namespace std; int main(){ double num=100*sqrt(2.0); cout<<"default:\t"<<num<<"\n" <<"scientific:\t"<<scientific<<num<<"\n" <<"fixed decimal:\t"<<fixed<<num<<"\n" <<"hexfloat:\t"<<hexfloat<<num<<"\n" <<"use default:\t"<<defaultfloat<<num<<"\n" <<"showpos:\t"<<showpos<<num<<"\n"; cout<<endl<<noshowpos; cout<<"default:\t"<<10.0<<endl; cout<<"noshowpoint:\t"<<noshowpoint<<10.0<<"\n"; cout<<"showpoint:\t"<<showpoint<<10.0<<"\n"; return 0; }
输出:
default: 141.421 scientific: 1.414214e+02 fixed decimal: 141.421356 hexfloat: 0x1.1ad7bc01366b8p+7 use default: 141.421 showpos: +141.421 default: 10 noshowpoint: 10 showpoint: 10.0000 按任意键继续
例3:输出补白。
#include<iostream> //#include<math.h> #include <iomanip> using namespace std; int main(){ int i=-16; double d=3.14159; //补白第一列,使用输出中最小12个位置 cout<<"i:"<<setw(12)<<i<<"next rol"<<"\n" <<"d:"<<setw(12)<<d<<"next rol"<<"\n"; //左对齐 cout<<left <<"i:"<<setw(12)<<i<<"next rol"<<"\n" <<"d:"<<setw(12)<<d<<"next rol"<<"\n"; //右对齐 cout<<right <<"i:"<<setw(12)<<i<<"next rol"<<"\n" <<"d:"<<setw(12)<<d<<"next rol"<<"\n"; //补在符号和值之间 cout<<internal <<"i:"<<setw(12)<<i<<"next rol"<<"\n" <<"d:"<<setw(12)<<d<<"next rol"<<"\n"; //使用#作为补白字符 cout<<setfill('#') <<"i:"<<setw(12)<<i<<"next rol"<<"\n" <<"d:"<<setw(12)<<d<<"next rol"<<"\n" <<setfill(' '); return 0; }
输出:
i: -16next rol d: 3.14159next rol i:-16 next rol d:3.14159 next rol i: -16next rol d: 3.14159next rol i:- 16next rol d: 3.14159next rol i:-#########16next rol d:#####3.14159next rol 按任意键继续
参考书籍:《Primer c++ 第五版》第17章