C++ 如何格式化输出 (cout)_C++ cout 格式化输出技巧与示例

C++中cout配合iostream和iomanip可实现格式化输出,1. 用setw()设置宽度,left/right控制对齐;2. setprecision()结合fixed、scientific控制浮点数精度与格式;3. dec、oct、hex进行进制转换输出,uppercase使十六进制字母大写;4. setfill()更改填充字符。注意setw仅对下次输出有效,而fixed、hex等状态持续生效,合理组合可使输出清晰美观。

在 C++ 中,cout 是最常用的输出工具,配合 iostream> 头文件,可以实现丰富的格式化输出功能。掌握这些技巧能让程序的输出更清晰、专业。

控制输出宽度与对齐方式

使用 setw() 设置字段宽度,leftright 控制对齐方式。

  • setw(n):设置下一个输出项的最小宽度为 n
  • left:左对齐
  • right:右对齐(默认)

示例:

#include 
#include 
using namespace std;

int main() {
    cout << setw(10) << "Hello" << setw(10) << "World" << endl;
    cout << left << setw(10) << "Hello" 
         << right << setw(10) << "World" << endl;
    return 0;
}

输出:

     Hello     World
Hello     World

设置浮点数精度与表示形式

setprecision() 控制小数位数或有效数字位数,结合 fixedscientific 调整显示格式。

  • setprecision(n):设置精度
  • fixed:固定小数点格式
  • scientific:科学计数法

示例:

double pi = 3.14159265358979;
cout << setprecision(6) << pi << endl;        // 默认:3.14159
cout << fixed << setprecision(3) << pi << endl; // 3.142
cout << scientific << pi << endl;              // 3.142e+00

进制转换输出

cout 支持十进制、八进制、十六进制输出,使用内置操纵符切换。

  • dec:十进制(默认)
  • oct:八进制
  • hex:十六进制
  • uppercase:十六进制字母大写

示例:

int num = 255;
cout << dec << num << endl;     // 255
cout << oct << num << endl;     // 377
cout << hex << num << endl;     // ff
cout << uppercase << hex << num << endl; // FF

填充字符设置

使用 setfill() 更改空白处的填充字符,默认为空格。

示例:

cout << setfill('*') << setw(10) << "Hi" << endl;

输出:

********Hi

基本上就这些常用技巧。灵活组合 setwsetprecisionsetfill 等操作符,能让你的输出整齐美观。注意这些格式化只对下一个输出项生效(如 setw),而状态类设置(如 fixed、hex)会持续生效直到更改。