cout的格式化输出

1、十进制、八进制、十六进制

cout << dec;      //十进制
cout << oct;      //八进制
cout << hex;      //十六进制,等同于hex(cout);

2、输出的宽度调整

cout.width(3);    //width()只对下一个将显示的内容起作用
cout << 1;        //显示“  1”

3、填充字符

cout.fill('*');    //使用*填充字段未被使用的部分,一直有效除非再次被更改

4、精度

cout.precision(2);  //精度设为2

5、setf()

  • 打印末尾的0和小数点
cout.setf(ios_base::showpoint);  //按照精度显示小数点及小数点后的0
  • fmtflags setf(fmtflags);
cout.setf(ios_base::boolalpha);
常量 含义
ios_base::boolalpha 输入和输出bool值,可以为true或false
ios_base::showbase 对于输出,使用C++基数前缀(0,0x)
ios_base::showpoint 显示末尾的小数点
ios_base::uppercase 对于16进制输出,使用大写字母,E表示法
ios_base::showpos 在正数前面加上+
  • fmtflags setf(fmtflags,fmtflags);
第二个参数 第一个参数 含义
ios_base::basefield ios_base::dec
ios_base::oct
ios_base::hex
使用基数10
使用基数8
使用基数16
ios_base::floatfield ios_base::fixed
ios_base::scientific
使用定点计数法
使用科学计数法
ios_base::adjustfield ios_base::left
ios_base::right
ios_base::internal
使用左对齐
使用右对齐
符号或基数前缀左对齐,值右对齐

eg.

ios_base::fmtflags old = cout.setf(ios_base::left, ios_base::adjustfield);  //设为左对齐
cout.setf(old, ios_base::adjustfield);      //恢复默认
//cout.unsetf(ios_base::adjustfield);       //恢复默认的另一种方式

6、标准控制符(更方便的用法)
eg.

cout << left << fixed;

提供包括boolalpha、noboolalpha、showbase、noshowbase、showpoint、noshowpoint、showpos、noshowpos、uppercase、nouppercase、internal、left、right、dec、hex、oct、fixed、scientific。

7、头文件iomanip

  • setprecision()
  • setw()
  • setfill()

eg.

#include 
……
cout << setprecision(2) << n;

你可能感兴趣的:(cout的格式化输出)