C++ cout格式化输出补0

#include <iostream>
#include<iomanip>
using namespace std;

int main()
{
        //左侧补零
	//只针对整数可行,因为没有浮点数左侧补零这种写法 如05.1
	int a = 5;
	cout << setw(3) << setfill('0') << a << endl;//005
	cout << a << endl;//5
	int b = 12;
	cout.width(4);
	cout.fill('0');
	cout << b << endl;//0012
	cout << b << endl;//12
	int c = 12, d = 34;
	cout << setw(3) << setfill('0') << c << " " << setw(3) << setfill('0') << d << endl;//012 034


	//右侧补零
        //只针对小数可行,整数不行,因为整数无法在后面补零
	float aa=0.25;
	cout << setiosflags(ios::fixed) << setprecision(3) << aa << endl;//0.250

	return 0;
}

 

 

  • 14
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
coutC++中的标准输出流对象,可以用于格式化输出。为了按照一定的格式进行输出,可以使用流操作算子或者成员函数进行控制。使用流操作算子时,可以使用一系列的格式控制符来指定输出的格式。例如,%X可以用于按十六进制输出整数,%.2f可以用于输出浮点数时保留小数点后面两位,setw()可以用于指定输出的宽度等。 需要注意的是,每次使用setw()设置输出宽度时,只会影响下一次的输出。如果需要多次指定输出宽度,需要在每次输出前使用setw()来设置。此外,setw()也可以影响cin在读入字符串时的行为。 以下是一个示例程序,演示了如何使用setw()和流操作算子进行格式化输出: #include <iostream> #include <iomanip> using namespace std; int main() { int num = 123; float f = 3.14159; cout << "Formatted output:" << endl; cout << "Number in hexadecimal: " << hex << num << endl; cout << "Float with 2 decimal places: " << fixed << setprecision(2) << f << endl; cout << "Number with width of 6, left-padded with 0: " << setw(6) << setfill('0') << num << endl; return 0; } 运行这段代码将会输出以下结果: Formatted output: Number in hexadecimal: 7b Float with 2 decimal places: 3.14 Number with width of 6, left-padded with 0: 000123 在上述示例中,我们先使用hex设置输出为十六进制形式,然后使用fixed和setprecision(2)设置浮点数的小数点位数,最后使用setw(6)和setfill('0')设置输出宽度为6,左侧用0填充。通过这些控制符,我们可以实现各种格式化的输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值