<iomanip> 是 C++ 中用于格式化输入输出的重要头文件,以下是常用函数和操纵符:

1. setw(int n) - 设置字段宽度

cout << setw(10) << "Hello" << endl;  // 输出: "     Hello"
cout << setw(5) << 123 << endl;       // 输出: "  123"

2. setprecision(int n) - 设置浮点数精度

double pi = 3.1415926;
cout << setprecision(3) << pi << endl;   // 输出: 3.14
cout << fixed << setprecision(2) << pi << endl; // 输出: 3.14 (固定小数位)
cout << scientific << setprecision(4) << pi << endl; // 输出: 3.1416e+00

3. setfill(char c) - 设置填充字符

cout << setfill('*') << setw(10) << 123 << endl;  // 输出: "*******123"
cout << setfill('0') << setw(5) << 42 << endl;    // 输出: "00042"

4. setbase(int base) - 设置进制

int n = 255;
cout << setbase(16) << n << endl;  // 输出: ff (十六进制)
cout << setbase(8) << n << endl;   // 输出: 377 (八进制)
cout << setbase(10) << n << endl;  // 输出: 255 (十进制)

5. setiosflags() / resetiosflags() - 设置/清除格式标志

cout << setiosflags(ios::left) << setw(10) << "Hello" << endl;  // 左对齐
cout << resetiosflags(ios::left) << setw(10) << "Hello" << endl; // 恢复右对齐

// 常用标志组合
cout << setiosflags(ios::fixed | ios::showpoint) << 123.0 << endl; // 输出: 123.00

6. 常用格式化标志

// 对齐方式
ios::left   // 左对齐
ios::right  // 右对齐(默认)
ios::internal // 符号左对齐,数值右对齐

// 数值格式
ios::dec    // 十进制
ios::hex    // 十六进制
ios::oct    // 八进制
ios::fixed  // 固定小数位
ios::scientific // 科学计数法
ios::boolalpha  // true/false 代替 1/0
ios::showpoint  // 显示小数点
ios::showpos    // 显示正数符号
ios::uppercase  // 十六进制大写

7. 完整示例

#include <iostream>
#include <iomanip>

int main() {
    double value = 123.456;
    
    // 格式化输出表格
    cout << left << setw(10) << "Number" 
         << right << setw(10) << "Value" << endl;
    cout << setfill('-') << setw(20) << "" << setfill(' ') << endl;
    
    cout << left << setw(10) << "Pi" 
         << fixed << setprecision(2) << setw(10) << 3.14159 << endl;
    
    cout << left << setw(10) << "E" 
         << scientific << setprecision(4) << setw(10) << 2.71828 << endl;
    
    // 格式化输出
    cout << showpos << setw(10) << 100 << endl;    // 输出: "+100"
    cout << noshowpos << endl; // 关闭正号显示
    
    // 布尔值输出
    cout << boolalpha << true << " " << false << endl;  // 输出: "true false"
    
    return 0;
}

8. 常用组合技巧

// 对齐填充
cout << left << setw(15) << setfill(' ') << "Name" << setw(10) << "Score" << endl;

// 货币格式化
double money = 1234.56;
cout << showpos << fixed << setprecision(2) << money << endl;  // +1234.56

// 十六进制输出大写
int num = 255;
cout << hex << uppercase << num << endl;  // "FF"

更多推荐