cout 輸出格式控制
如果要在輸出資料流中加入格式控制符則要載入標頭檔:#include <iomanip>
這裡面 iomanip 的作用比較多:
主要是對 cin,cout 之類的一些操縱運運算元,比如 setfill,setw,setbase,setprecision 等等。它是 I
/O 流量控制標頭檔,就像 C 裡面的格式化輸出一樣.以下是一些常見的控制函數的:
dec 置基數為 10 相當於"%d"
hex 置基數為 16 相當於"%X"
oct 置基數為 8 相當於"%o"
sample://作用永久
cout<<12<<hex<<12<<oct<<12<<12;output 12c1414
setprecision(n) 設顯示小數精度為 n 位 //作用永久
sample: setf(ios:fixed);
cout<<setprecision(2)<<2.345<<endl; ouput 2.34 //注意先用 setf(ios::fixed);否則結果自己測試下
setw(n) 設域寬為 n 個字元 //作用臨時
這個控制符的意思是保證輸出寬度為 n。如:
cout<<setw(3)<<1<<setw(3)<<10<<setw(3)<<100;輸出結果為
1 10100 (預設是靠右對齊)當輸出長度大於 3 時(<<1000),setw(3)不起作用。
setfill(c) 設填充字元為 c
setioflags(ios::fixed)固定的浮點顯示
setioflags(ios::scientific) 指數表示
sample cout<<setiosflags(ios::fixed)<<setprecision(2)<<2.345<<endl; output 2.34
setiosflags(ios::left) 靠左對齊
setiosflags(ios::right) 靠右對齊
setiosflags(ios::skipws) 忽略前置空白
setiosflags(ios::uppercase) 16 進位數大寫輸出
setiosflags(ios::lowercase) 16 進位小寫輸出
setiosflags(ios::showpoint) 強制顯示小數點
setiosflags(ios::showpos) 強制顯示符號
sample: cout<<setiosflags(ios::uppercase)<<hex<<12<<15<<endl; output CF
cout<<setioflags(ios::showpoint)<<x<<endl;
若 float x=1,則 output 1.000000 不使用直接輸出 1
cout<<setiosflags(ios::showpos)<<1<<endl;output +1