【筆記】iomanip

  • IO manipulation:控制輸出格式
  • setbase(): 更改數字的進位制(設定後持續有效)
  • setprecision():設定十進位浮點數的精確度(設定後持續有效)。可搭配 fixed 來鎖定小數點後的位數。
  • setw():設定列印時的欄位寬度,若為浮點數,小數點也佔一位。(設定後單次有效)。
  • setfill():指定列印的欄位寬度後,設定左方不足位數要填補的字元符號,預設為空白字元。(設定後持續有效)
// setbase(): 設定後持續有效
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int n = 127;
    cout << n << endl;
    cout << "oct (base =  8): " << setbase(8) << n << endl;
    cout << "dec (base = 10): " << setbase(10) << n << endl;
    cout << "hex (base = 16): " << setbase(16) << n << endl;
    cout << n << endl;
}
Output:
127
oct (base =  8): 177
dec (base = 10): 127
hex (base = 16): 7f
7f
// setprecision()
// fixed
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double PI = 3.1415926;
    cout << PI << endl;
    cout << setprecision(4) << PI << endl;
    cout << fixed << setprecision(4) << PI << endl;
    cout << PI << endl;
}
Output:
3.14159
3.142
3.1416
3.1416
// setw()
// setfill()
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int n = 1024;
    double PI = 3.1415926;
    cout << n << endl;
    cout << setw(8) << n << endl;
    cout << setw(8) << setfill('0') << n << endl;
    cout << setw(8) << PI << endl;
    cout << setw(8) << fixed << setprecision(4) << PI << endl;
}
Output:
1024
    1024
00001024
03.14159
003.1416
分享本文 Share with friends