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> 和 <iomanip> 头文件,可以实现丰富的格式化输出功能。掌握这些技巧能让程序的输出更清晰、专业。
使用 setw() 设置字段宽度,left 和 right 控制对齐方式。
示例:
#include <iostream>
#include <iomanip>
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;
}
输出:
立即学习“C++免费学习笔记(深入)”;
Hello World Hello World
用 setprecision() 控制小数位数或有效数字位数,结合 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 支持十进制、八进制、十六进制输出,使用内置操纵符切换。
示例:
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;
输出:
立即学习“C++免费学习笔记(深入)”;
********Hi
基本上就这些常用技巧。灵活组合 setw、setprecision、setfill 等操作符,能让你的输出整齐美观。注意这些格式化只对下一个输出项生效(如 setw),而状态类设置(如 fixed、hex)会持续生效直到更改。
以上就是C++ 如何格式化输出 (cout)_C++ cout 格式化输出技巧与示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号