用setw( )设置字段宽

setw头文件是什么?

setw是什么意思?

setw 默认是右对齐,如何设置其左对齐?

setw函数头文件要加上#include<iomanip>,我们可以用setw( )设置字段宽 ,setw函数默认是右对齐,而且该函数对字段宽的设置仅一次有效,对后面的输出并无影响(如例子一对16的输出并无影响)。

 

应用举例一:

如果直接用cout<<setw(5)<<123<<16<<endl;

代码演示

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

int main()
{
	cout<<setw(5)<<123<<16<<endl;

	return 0;
}


 

则输出结果为  12316(数字12316前面有2个空格)

 

应用举例二:

设置填充字符一般用cout.fill('*'),要左对齐的话用cout.setf(ios::left,ios::adjustfield);右对齐类似。所以上面的程序写成:

cout.setf(ios::left,ios::adjustfield);

cout.fill('*');

cout<<setw(5)<<123<<16<<endl;

代码演示

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

int main()
{
	cout.setf(ios::left,ios::adjustfield);
	cout.fill('*');
	cout<<setw(5)<<123<<16<<endl;

	return 0;
}


输出结果为123**16

 

应用举例3:

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

int main()
{
   //cout<<setw(10)<<setfill(*)<<1234;
   cout<<setw(10)<<setfill('*')<<1234<<endl;
   cout << setw(10) << setfill('*') << left << 1234<<endl;
   //cout << setw(10) << setfill("*") << left << 1234<<endl;

   return 0;
}


因为数据的输出默认是右,如果你想输出为1234***……可以加个left,如cout << setw(10) << setfill('*') << left << 1234;

如果写为cout<<setw(10)<<setfill(*)<<1234会报错,因为缺少了单引号。

如果用双引号也会报错。

VC++输出结果:

******1234

1234******

 

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值