天天看點

C++ stw與setfill

注意問題:

所使用的頭檔案為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;
}
           
C++ stw與setfill