cout 常用成员函数简介(C++输出格式控制)

控制输出宽度(占位)

cout.width(int length);

常与 cout.flags(ios::left) or cout.flags(ios::right) 搭配使用,来控制居左、居右输出
作用域:只能控制下面一句 cout 输出!
例:

string s = "she";
char ch = 'v';

cout.width(5);
cout.flags(ios::right);

cout << s << endl;	// __she,起作用
cout << ch << endl;	// v,未起作用

控制占位填充字符

cout.fill(char c)

cout.width(int length)搭配使用,用字符填充空白
作用域:只能控制下面一句 cout 输出!
例:

cout.fill('0');
cout.width(3);

int a = 1;
int b = 2;

cout << a << endl;	// 001
cout << b << endl;	// 2

// 如果想要一直保持此格式,可在每一次输出前加一句 cout.width();
for (int i = 0; i < 3; i++)
{
	cout.width(3);
	cout << i << endl;
}
// 000
// 001
// 002

控制小数输出位数

cout.flags(ios::fixed);搭配使用,控制小数输出位数,如果不加cout.flags(ios::fixed);而仅使用cout.precision(int len);则任何效果!

cout.precision(int len);	// 保留 len 位小数
cout.flags(ios::fixed);

作用域:能控制下面所有的浮点数输出!
例:

float a = 2.4423;
double b = 2.1;

cout.precision(3);	// 保留 3 位小数
cout.setf(ios::fixed);

cout << a << endl;	// 2.442
cout << b << endl;	// 2.100

取消此效果用cout.unsetf(ios::fixed);

输出非负数的正号

cout.flags(ios::showpos);

作用域:能控制下面所有的数字输出!
例:

cout.flags(ios::showpos);

int a1 = 0;
cout << 3.12 << endl;	// +3.12
cout << a1 << endl;		// +0

取消此效果用cout.unsetf(ios::showpos);

使用 8/10/16 进制输出整数

一般情况下,是默认十进制输出

cout.flags(ios::oct);
cout.flags(ios::dec);
cout.flags(ios::hex);

作用域:能控制下面所有的数字输出!
例:

int a = 12;

cout.flags(ios::oct);
cout << a << end;	// 14

cout.flags(ios::dec);
cout << a << end;	// 12

cout.flags(ios::hex);
cout << a << end;	// c

直接输出数据,不受格式化参量影响

cout.put(char c);

直接输出一个字符,不受流的格式化参量影响
例:

cout.fill('*');
cout.width(3);

cout.put('a') << endl;	// a

cout.width(3);
cout << 'a' << endl;	// **a

更多

详见官网

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值