<iomanip>,插入流中即時生效,可串聯cout 物件方法,定義於 <iostream>,無需額外標頭檔| 功能 | 控制元 | 成員函式 | 說明 |
|---|---|---|---|
| 進制 | dec/hex/oct, setbase(n) | setf(ios::dec/hex/oct) | 互斥,需先 unsetf |
| 顯示基數前綴 | showbase | setf(ios::showbase) | 0x, 0 等 |
| 域寬 | setw(n) | width(n) | 僅影響下一個輸出項 |
| 填充字元 | setfill(c) | fill(c) | 配合域寬使用 |
| 對齊 | left/right/internal | setf(ios::left/right/internal) | 域寬內對齊方式 |
| 浮點精度 | setprecision(n) | precision(n) | 有效位數或小數位數 |
| 浮點格式 | scientific/fixed | setf(ios::scientific/fixed) | 科學記號 vs 定點 |
| 強制小數點 | showpoint | setf(ios::showpoint) | 保留尾隨 0 |
| 正數顯示 + | showpos | setf(ios::showpos) | |
| 大寫科學記號 | uppercase | setf(ios::uppercase) | E vs e, 0X vs 0x |
#includeint a = 34; cout << "dec:" << dec << a << endl << "hex:" << hex << a << endl << "oct:" << setbase(8) << a << endl; char* pt = "China"; cout << setw(10) << pt << endl << setfill('*') << setw(10) << pt << endl; double pi = 22.0/7.0; cout << scientific << setprecision(8) << "pi=" << pi << endl << setprecision(4) << "pi=" << pi << endl << fixed << "pi=" << pi << endl;
int a = 21;
cout.setf(ios::showbase);
cout << "dec:" << a << endl;
cout.unsetf(ios::dec); cout.setf(ios::hex); cout << "hex:" << a << endl;
cout.unsetf(ios::hex); cout.setf(ios::oct); cout << "oct:" << a << endl;
cout.width(10); cout << "China" << endl;
cout.width(10); cout.fill('*'); cout << "China" << endl;
double pi = 22.0/7.0;
cout.setf(ios::scientific); cout.width(14); cout << "pi=" << pi << endl;
cout.unsetf(ios::scientific); cout.setf(ios::fixed);
cout.width(12); cout.setf(ios::showpos | ios::internal); cout.precision(6);
cout << pi << endl; // +***3.142857
width/setw 只對緊隨其後的第一個輸出項有效dec/hex/oct 三選一,切換前必須 unsetf 舊旗標setf(ios::internal | ios::showpos) 可一次設多個非互斥旗標unsetf;控制元多為一次性 (除 setiosflags)掌握雙軌制格式控制,理解「一次性域寬」「互斥進制旗標」「持久狀態管理」三大核心規則,即能輸出完美對齊、進制正確、精度可控的專業級文字報表。