天天看點

用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個空格)

用setw( )設定字段寬

應用舉例二:

設定填充字元一般用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

用setw( )設定字段寬

應用舉例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******

用setw( )設定字段寬

繼續閱讀