C++ 輸出格式控制有兩種等價方式:流操縱算子(需 <iomanip>)和 流成員函數(無需額外頭文件)。本文系統對比兩種用法,涵蓋寬度、對齊、填充、精度、進制五大控制類別。
int n = 64; double d = 123.45; double d2 = 0.0183;
#include <iomanip> #include <iostream> using namespace std;
setw(w)僅影響下一個輸出項,默認右對齊,不足填充空格。
cout << n << '#' << endl; // 64# cout << setw(10) << n << '#' << endl; // [空格×6]64# cout << n << '#' << endl; // 64#(寬度不持久)

setiosflags(ios::left/right)持久生效,直到重置。resetiosflags 可撤銷。
cout << setw(10) << setiosflags(ios::left) << n << '#' << endl; // 64[空格×6]# cout << setw(10) << n << '#' << endl; // 仍左對齊 cout << setw(10) << setiosflags(ios::right) << n << '#' << endl; // 恢復右對齊 // 或:cout << setw(10) << resetiosflags(ios::left) << n << '#' << endl;

setfill(c)持久生效,默認空格。
cout << setw(10) << setfill('@') << n << '#' << endl; // @@@@@@64#
cout << setw(10) << n << '#' << endl; // 仍用 @ 填充
cout << setw(10) << setfill(' ') << n << '#' << endl; // 恢復空格

setprecision(p)默認控制有效數字總位數(科學計數法),四捨五入。配合 ios::fixed 控制小數點後位數。
cout << setprecision(4) << d << endl; // 123.5(4 位有效數字) cout << setprecision(2) << d2 << endl; // 0.018(4 捨五入) cout << d << endl; // 123.45(恢復默認精度 6) cout << setiosflags(ios::fixed); // 固定小數點模式 cout << setprecision(4) << d << endl; // 123.4500(小數點後 4 位) cout << setprecision(2) << d2 << endl; // 0.02

cout << "dec: " << dec << n << endl; // 64 cout << "oct: " << oct << n << endl; // 100 cout << "hex: " << hex << n << endl; // 40

所有操作通過 cout 對象方法完成,狀態持久。
cout.width(w)cout << n << endl; cout.width(10); cout << n << '#' << endl; // 僅影響這次輸出

cout.setf(ios::left) / cout.unsetf(ios::left)cout.width(10); cout.setf(ios::left); cout << n << '#' << endl; // 左對齊 cout.width(10); cout.unsetf(ios::left); // 取消左對齊 → 右對齊 cout << n << '#' << endl;

cout.fill(c)cout.width(10);
cout.fill('@');
cout << n << '#' << endl; // @@@@@@64#
cout.width(10);
cout << n << '#' << endl; // 仍用 @
cout.width(10);
cout.fill(' ');
cout << n << '#' << endl; // 恢復空格

cout.precision(p) + cout.setf(ios::fixed)cout.precision(2); cout << d << endl; // 1.2e+02(科學計數法,2 位有效數字) cout << d2 << endl; // 0.018 cout.setf(ios::fixed); cout << d << endl; // 123.45(小數點後 2 位) cout << d2 << endl; // 0.02

cout.unsetf(ios::dec); // 必須先取消當前進制 cout.setf(ios::oct); cout << n << endl; // 100
| 特性 | 操縱算子 | 成員函數 |
|---|---|---|
| 頭文件 | <iomanip> | <iostream> 即可 |
| 調用風格 | 鏈式 cout << setw(10) << n | 語句式 cout.width(10); cout << n |
| 持久性 | 對齊/填充/精度/進制持久,寬度單次 | 全部持久 |
| 重置方式 | resetiosflags | unsetf |
| 推薦場景 | 臨時格式調整、代碼緊湊 | 長期統一格式設置 |
實際開發中常混合使用:用成員函數設置全局默認格式,用操縱算子做局部微調。