首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 基礎

C++ 輸出格式控制大全:控制元 vs 成員函式雙軌並行

     編輯:C++ 基礎

兩種控制方式

  1. 控制元:定義於 <iomanip>,插入流中即時生效,可串聯
  2. 成員函式:cout 物件方法,定義於 <iostream>,無需額外標頭檔

常用格式控制對照表

功能控制元成員函式說明
進制dec/hex/oct, setbase(n)setf(ios::dec/hex/oct)互斥,需先 unsetf
顯示基數前綴showbasesetf(ios::showbase)0x, 0 等
域寬setw(n)width(n)僅影響下一個輸出項
填充字元setfill(c)fill(c)配合域寬使用
對齊left/right/internalsetf(ios::left/right/internal)域寬內對齊方式
浮點精度setprecision(n)precision(n)有效位數或小數位數
浮點格式scientific/fixedsetf(ios::scientific/fixed)科學記號 vs 定點
強制小數點showpointsetf(ios::showpoint)保留尾隨 0
正數顯示 +showpossetf(ios::showpos)
大寫科學記號uppercasesetf(ios::uppercase)E vs e, 0X vs 0x

控制元範例:串聯靈活

#include 
int 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) 可一次設多個非互斥旗標
  • 持久 vs 暫時:成員函式設定持久有效直到 unsetf;控制元多為一次性 (除 setiosflags)

選擇建議

  • 臨時、單次格式調整 → 控制元 (串聯直觀、無殘留狀態)
  • 長期、全域格式風格 → 成員函式 (集中管理、效能略優)
  • 現代 C++ 建議:優先使用控制元,代碼更清晰、少副作用

總結

掌握雙軌制格式控制,理解「一次性域寬」「互斥進制旗標」「持久狀態管理」三大核心規則,即能輸出完美對齊、進制正確、精度可控的專業級文字報表。

  1. 上一篇文章:
  2. 下一篇文章:
  • --热点文章
  • Copyright © 程式碼之家 All Rights Reserved