C++中如何用cout实现输出的位度,填充等控制

对于位宽和填充方式的控制,如下程序所示:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
	double y = 19.0123456789;
	int x = 65;

	cout.fill('0');       //设置填充方式为0;
	cout << setw(5) << x << endl;//控制输出位宽为5,右对齐。

	cout.setf(ios::left); //设置对齐方式为left 
	cout.width(7); //设置宽度为7,不足用空格填充 
	cout << "1.1" << endl;

	cout.unsetf(ios::left); //取消对齐方式,用缺省right方式 
	cout.fill('.'); //设置填充方式 
	cout.width(30); //设置宽度,只对下条输出有用 
	cout << 1 << endl;

	cout << setiosflags(ios::left) << setw(7); //设置宽度为7,left对齐方式 
	cout << 1.1 << endl;

	cout << resetiosflags(ios::left); //取消对齐方式 
	cout << setfill('.') << setw(30) << 1 << endl; //宽度为30,填充为'.'输出 

	cout << y << setprecision(4) << endl;//控制输出精度

	return 0;
}

输出:

00065
1.10000
..........................1
1.1....
..........................1
19.0123

对于浮点数的输出控制如下程序所示:

#include <iostream> 
void main()
{
	float f = 2.0 / 3.0, f1 = 0.000000001, f2 = -9.9;
	cout << f << ' ' << f1 << ' ' << f2 << endl; //正常输出 
	cout.setf(ios::showpos); //强制在正数前加+号 
	cout << f << ' ' << f1 << ' ' << f2 << endl;
	cout.unsetf(ios::showpos); //取消正数前加+号 
	cout.setf(ios::showpoint); //强制显示小数点后的无效0 
	cout << f << ' ' << f1 << ' ' << f2 << endl;
	cout.unsetf(ios::showpoint); //取消显示小数点后的无效0 
	cout.setf(ios::scientific); //科学记数法 
	cout << f << ' ' << f1 << ' ' << f2 << endl;
	cout.unsetf(ios::scientific); //取消科学记数法 
	cout.setf(ios::fixed); //按点输出显示 
	cout << f << ' ' << f1 << ' ' << f2 << endl;
	cout.unsetf(ios::fixed); //取消按点输出显示 
	cout.precision(18); //精度为18,正常为6 
	cout << f << ' ' << f1 << ' ' << f2 << endl;
	cout.precision(6); //精度恢复为6 
}

还可以用操纵算子来实现:

#include <iostream>
#include <iomanip> 
using namespace std;
int main()
{
	float f = 2.0 / 3.0, f1 = 0.000000001, f2 = -9.9;
	cout << f << ' ' << f1 << ' ' << f2 << endl; //正常输出 
	cout << setiosflags(ios::showpos); //强制在正数前加+号 
	cout << f << ' ' << f1 << ' ' << f2 << endl;
	cout << resetiosflags(ios::showpos); //取消正数前加+号 
	cout << setiosflags(ios::showpoint); //强制显示小数点后的无效0 
	cout << f << ' ' << f1 << ' ' << f2 << endl;
	cout << resetiosflags(ios::showpoint); //取消显示小数点后的无效0 
	cout << setiosflags(ios::scientific); //科学记数法 
	cout << f << ' ' << f1 << ' ' << f2 << endl;
	cout << resetiosflags(ios::scientific); //取消科学记数法 
	cout << setiosflags(ios::fixed); //按点输出显示 
	cout << f << ' ' << f1 << ' ' << f2 << endl;
	cout << resetiosflags(ios::fixed); //取消按点输出显示 
	cout << setprecision(18); //精度为18,正常为6 
	cout << f << ' ' << f1 << ' ' << f2 << endl;
	cout << setprecision(6); //精度恢复为6 
	return 0;
}
  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值