C++格式化输出、格式化控制

#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"
*/




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值