c++中的setfill和sew的应用

来源:百度知道 编辑:UC知道 时间:2024/05/25 01:53:57
1.
#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
for(int n=1;n<=10;++n)
cout<<setfill(' ')<<setw(n)<<" "
<<setfill('M')<<setw(21-2*n)<<"M"<<endl;
}

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

int main()
{
for(int n=1;n<=10;++n)
cout<<setfill(' ')<<setw(n)
<<setfill('M')<<setw(21-2*n)<<"M"<<endl;
}

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

int main()
{
for(int n=1;n<=10;++n)
cout<<cout.fill(' ')<<cout.width(n)<<" "
<<cout.fill('M')<<cout.width(21-2*n)<<"M"<<end

setfill是设置填充填充字符,setw设置输出的宽度,它们的只作用表现在紧接着输入的字符串上。这个宽度是填充后的宽度。所以

cout<<setfill(' ')<<setw(n)<<" " << setfill("M")<<setw(21-2*n)<<"M"中
setfill和setw只作用在" ",表示在" "前面填充n-1个空白。
而setfill("M")<<setw(21-2*n)<<"M"这一段是在"M"前面填充21-2*n-1个空白。

cout<<setfill(' ')<<setw(n)<<setfill("M")<<setw(21-2*n)<<"M"
是不一样的。
后者的因为setfill("M")不是一个字符,这种情况没有明确的说明该如何处理。从我用的VC输出的情况分析,处理方法是前面的setfill和setw失去了作用。
至于cout.width和count.fill一般是这样用的:
cout.width(n);
cout.fill('M');
cout << ...
如果是cout << cout.width(n)就是输出 cout.width(n)的返回值。表示设置的流的宽度,所以似乎一个数。至于为什么会输出这样的数值。分析起来比较麻烦,涉及到运算顺序一类的问题,而且也可能和编译器的实现方法有关,没有什么实际意义,还是老老实实分开写比较好。