注意問題:
所使用的頭檔案為iomanip.h
例如:
cout<<'s'<<setw(8)<<'a'<<endl;
則在螢幕顯示
s a
//s與a之間有7個空格,setw()隻對其後面緊跟的輸出産生作用,如上例中,表示'a'共占8個位置,不足的用空格填充。若輸入的内容超過setw()設定的長度,則按實際長度輸出。
setw()預設填充的内容為空格,可以setfill()配合使用設定其他字元填充。
如
cout<<setfill('*')<<setw(5)<<'a'<<endl;
則輸出:
****a //4個*和字元a共占5個位置。
ep:
// test_max.cpp : 定義控制台應用程式的入口點。
#include "stdafx.h"
#include <iostream>
#include <iomanip> //setw(),setfill所在頭檔案
using namespace std;
class NUM
{
public:
NUM(int i):nm(i){}
void incr() const
{
nm++;
}
void decr() const
{
nm--;
}
public:
mutable int nm;
};
int main(void)
{
NUM a(0);
string str="";
for(int i=0;i<5;i++)
{
a.incr();
cout<<setfill('*')<<setw(a.nm)<<str.c_str()<<endl;
}
for(int i=0;i<5;i++)
{
a.decr();
cout<<setw(a.nm)<<str.c_str()<<setfill('*')<<endl;
}
system("pause");
return 0;
}
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0NXYFhGd192UvwVe0lmdhJ3ZvwFM38CXlZHbvN3cpR2Lc1TPB10QGtWUCpEMJ9CXsxWam9CXwADNvwVZ6l2c052bm9CXUJDT1wkNhVzLcRnbvZ2LclXS61EeFpWTqBnMZZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39TNyYDN1gzMwEDMxUDM0EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)