C++ 头文件 iomanip
iomanip是I/O流控制头文件,主要是对cin和cout操纵的算子。(io是input、output(输入输出),manip是manipulator(操纵器,操纵算子))
1.设置字段宽度setw(int n) - cout << setw(5) << 248 << endl;
- 运行结果
- 248
复制代码
2.流输出进制
dec 置基数为10 相当于"%d" hex 置基数为16 相当于"%X" oct 置基数为8 相当于"%o" 流输出二进制需要包含 头文件,调用bitset(int n)函数将十进制输出为二进制 - cout << hex << 255 << endl;
- cout << bitset<11>(255) << endl;
- 运行结果
- ff
- 00011111111
复制代码
3.填充字符setfill(char c)
在预设宽度中,如果存在没有用完的宽度大小,则用字符c填充 - cout << setfill('0') << setw(6) << 248 << endl;
- 运行结果:
- 000248
复制代码
4.进制转换setbase(int n)
将某一个十进制数转换为一个n进制的数,实际上只能是8和16进制,如果是2~36任意进制还是使用头文件中itoa()函数。 - cout<< setbase(8) << setw(5) << 255 << endl;
- 运行结果:
- 377
复制代码
5.设置小数精度setprecision(int n)
控制输出流显示浮点数的数字个数(包括整数部分),默认的流输出数值有效位是6。 - cout << setprecision(3) << 22.123 << endl;
- cout << setprecision(8) << 22.123 << endl; //比原字符长不会补零!
- 运行结果:
- 22.1
- 22.123
复制代码
6.设置格式标志setiosflags(ios_base::fmtflags mask)
用setiosflags(ios::fixed)或者直接用fixed都行
方法 | 格式 |
---|
setiosflags(ios::scientific) | 是用指数方式表示实数 | setiosflags(ios::fixed) | 固定的浮点显示 | setiosflags(ios::scientific) | 指数表示 | setiosflags(ios::left) | 左对齐 | setiosflags(ios::right) | 右对齐 | setiosflags(ios::skipws) | 忽略前导空白 | setiosflags(ios::uppercase) | 16进制数大写输出 | setiosflags(ios::lowercase) | 16进制小写输出(VS2010中该方法已不使用,意外使用显示没有该成员错误) | setiosflags(ios::showpoint) | 强制显示小数点 | setiosflags(ios::showpos) | 强制显示符号 | - cout<< fixed << setw(10) << 3.1415926 << endl;
- cout<< setiosflags(ios::fixed) << setw(10) << 3.1415926 << endl;
- 运行结果:
- 3.141593
- 3.141593
复制代码
6.重置格式标志resetiosflags(ios_base::fmtflags mask)
终止已经设置的输出格式状态,在括号中应指定内容 - cout << fixed << setw(10) << 3.1415926 << endl;
- cout << resetiosflags(ios::fixed) << setw(10) << 3.1415926 << endl;
- cout << hex << showbase << 100 << endl;
- cout << resetiosflags(ios::showbase) << 100 << endl;
- 运行结果:
- 3.141593
- 3.14159
- 0x64
- 64
复制代码
转载来源:
C/C++笔试必须熟悉掌握的头文件系列(十)——iomanip.h/iomanip
C++ 标准库之iomanip
std::resetiosflags()函数 |