close

按此前往C++完整教學目錄

 

 

在上一篇:輸出排版中提到,排版時要在每一個cout物件之前設定cout.width()

若嫌這樣太過麻煩,可利用setw(n)函式來設定n個預留的空白字元,而使用前要在標頭檔加上#include <iomanip>

使用方法例如:

cout<<setw(5)<<"aaa"<<setw(5)<<"bbb"<<"ccc";

顯示結果為  aaa  bbbcc

(2)對於大量排版輸出,上述方法還是很麻煩,且容易寫錯。此時,建議使用自定函式來解決,如:

void my_out(int n,string s1,string s2,string s3,string s4,string s5,string s6)

{cout.setf(ios_base::left,ios_base::adjustfield);

cout.width(n);cout<<s1;

cout.width(n);cout<<s2;

cout.width(n);cout<<s3;

cout.width(n);cout<<s4;

cout.width(n);cout<<s5;

cout.width(n);cout<<s6;

cout<<endl;

cout.setf(ios_base::right,ios_base::adjustfield);}

int main()  //主程式在此

{

my_out(6,"name","age","level","hp","mp","score");

my_out(6,"weiwei","18","1","50","20","95");

my_out(6,"nunu","20","1","60","12","92");

}

執行後的即可顯示排版結果。

 

arrow
arrow

    埃伯 發表在 痞客邦 留言(0) 人氣()