#include<iostream>
#include"iomanip"
using namespace std;
int main()
{
int a = 19;
double d = 123.1234567;
char c[100];
cout << "以下是控制符:" << endl;
cout << setprecision(5) << d << endl; //输出123.12 //设置精度为5,整数位和小数位共5位
cout << setprecision(10) << d << endl;//输出123.1234567 //设置精度为15,但不会在末尾补0
cout << setprecision(10) << setiosflags(ios::fixed) << d << endl;//输出123.1234567000 //设置精度为10,则小数位为10位,即浮点数以“定点格式”输出
cout << resetiosflags(ios::fixed);//取消“定点格式”输出
cout << setw(24) << setfill('&') << d << endl;//输出&&&&&&&&&&&&&123.1234567 //setw(24)不是永久有效,只在本次输出中有效。
cout << d << endl;//输出 123.1234567 //上一句的setw(24)已经失效
cout << setw(24) << setprecision(0) << d << endl;//输出 &&&&&&&&&&&&&&&&&123.123 //取消精度可以用“setprecision(0)”,恢复为默认的6位精度
cout << setw(24) << setprecision(12) << setiosflags(ios::left) << d << endl;//输出 123.1234567&&&&&&&&&&&&& //设置左对齐
cout << setw(24) << setprecision(12) << setiosflags(ios::internal) << setiosflags(ios::showpos) << d << endl;//输出 &&&&&&&&&&&&+123.1234567 //很奇怪,internal效果应该是“+”左对齐,数值右对齐
cout << setw(24) << resetiosflags(ios::showpos) << d << endl; //输出 &&&&&&&&&&&&&123.1234567 //取消“+”的显示
cout << setw(24) << setprecision(12) << internal << showpos << d << endl;//输出 +&&&&&&&&&&&&123.1234567 //巧合?internal、showpos可以直接使用
cout << setw(24) << setfill('*') << setprecision(6) << setiosflags(ios::scientific) << d << endl;//输出+**********1.231235e+002 //设置精度为6,科学计数法的精度为小数点后位数
cout << setw(24) << resetiosflags(ios::scientific) << d << endl;//输出+****************123.123 //取消控制符“scientific”作用,用“resetiosflags”
cout << "以下是流成员函数:" << endl;
cout.precision(5);
cout.width(24);
//cout.setf(ios::right);
cout.setf(ios::internal);
//cout.setf(ios::dec);
//cout.setf(ios::oct);
//cout.setf(ios::hex);
cout << d << endl;//输出+*****************123.12
cout << d << endl;//输出+123.12 //width依然不是永久有效,只在本次输出中有效
cout.setf(ios::scientific);
cout.setf(ios::uppercase);//大写显示科学计数法的“E”以及16进制的字母
cout << d << endl;//输出 +1.23123E+002
cout.unsetf(ios::uppercase);//取消用“unsetf”
cout.width(24);
cout << d << endl;//输出 +***********1.23123e+002
cout.width(24);
cout.fill(' ');
cout << d << endl;//输出 + 1.23123e+002
system("pause");
return 0;
}
/*
总结:
1.字段宽度cout.width(n)或setw(n)是一次性的
2.如果使用了控制符则需要加头文件"iomanip"
*/
C++格式化输出、格式化控制
最新推荐文章于 2024-08-08 11:38:49 发布