用setw( )设置字段宽

来源:互联网 发布:葡萄牙 法国 知乎 编辑:程序博客网 时间:2024/05/29 15:48

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******

 

1 0
原创粉丝点击