在 C 中,我们使用 printf 输出内容时,可以使用多种格式控制方法,比如 %x %d %f %p 等等,但在 C++ 的io流输入输出的类中,我们找不到这些方法也不知道如何实现这些功能了。本文就介绍一些 C++ 中,io流输入输出格式控制的函数。

#include
#include
 
using namespace std;
 
int main(int argc, char* argv[])
{
// 位宽度10 setw
cout << setw(10) << 1234 << endl;
 
// 位宽度10,左对齐 setiosflags
cout << setw(10) << setiosflags(ios::left) << 1234 << endl;
 
// 位宽度10,左对齐,填充为* setfill
cout << setw(10) << setiosflags(ios::left) << setfill(‘*‘) << 1234 << endl;
 
// 强制输出小数点和尾 showpoint
double b = 1.23;
cout << setiosflags(ios::showpoint) << b << endl;
 
// 强制显示符号 showpos
// 类似于 cout.operator<<(setiosflags(ios::showpos))
// setiosflags(ios::showpos) 只是一个参数
cout << -1 << endl;
cout << setiosflags(ios::showpos) << 1 << endl;
cout << resetiosflags(ios::showpos);
 
// 强制不以科学计数发输出
double c = 1234567123.5;
cout << c << endl;
cout << setiosflags(ios::fixed) << c << endl;
 
// 设置精度
double d = 123.456789;
cout << setprecision(0) << d << endl;
cout << setprecision(2) << d << endl;
cout << setprecision(4) << d << endl;
cout << setprecision(6) << d << endl;
cout << setprecision(8) << d << endl;
cout << setprecision(10) << d << endl;
 
// 输出十六进制时控制字母的大小写
int e = 1234;
cout << hex << setiosflags(ios::uppercase) << e << endl;
cout << hex << resetiosflags(ios::uppercase) << e << endl;
 
// 输出十六进制的0x 8进制的0
cout << hex << setiosflags(ios::showbase) << e << endl;
cout << oct << setiosflags(ios::showbase) << e << endl;
 
return 0;

}