<iostream> 配合 <iomanip> 提供豐富的格式化控制,如進位制、布林值顯示、浮點精度、寬度、填充字元等。修改格式旗標會影響後續輸出,需及時重置。
std::boolalpha / std::noboolalpha:布林值顯示 true/false 或 1/0。std::oct, std::hex, std::dec:八/十六/十進位輸出整數。std::showbase:顯示進位制前綴(0x 等)。std::uppercase / std::nouppercase:十六進位字母大小寫。std::fixed, std::scientific:浮點數固定/科學記號。std::setprecision(n):設定浮點數精度。std::setw(n), std::setfill(c):欄位寬度與填充字元。std::left, std::right, std::internal:對齊方式。/* cppprimer.cpp
* Created on: 2013.11.28
* Author: Caroline
*/
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << "default bool: " << true << " " << false << "\n";
cout << "boolalpha: " << boolalpha << true << " " << false << endl;
cout << noboolalpha << "reset: " << true << " " << false << endl;
cout << hex << showbase << uppercase << 255 << endl; // 0XFF
cout << nouppercase << 255 << endl; // 0xff
cout << dec << 255 << endl;
cout << fixed << setprecision(2) << 3.14159 << endl; // 3.14
cout << scientific << setprecision(3) << 1234.5 << endl; // 1.235E+03
cout << setw(10) << setfill('*') << left << "Hello" << endl; // Hello*****
return 0;
}
std::hex 讀取十六進位整數)。std::ostringstream 進行字串格式化,避免汙染標準輸出流狀態。