C6.【C++ Cont】cout的格式输出

目录

1.头文件

2.使用

1.控制宽度和填充

[setw函数(全称set field width设置字段宽度)](#setw函数(全称set field width设置字段宽度))

[setfill函数(全称Set fill character设置填充字符)](#setfill函数(全称Set fill character设置填充字符))

2.控制数值格式

3.控制整数格式

4.控制对齐方式


1.头文件

用cout进行格式化输出前,先引用头文件iomanip(全称i nput&o utput manipulators)

cpp 复制代码
#include <iomanip>

2.使用

1.控制宽度和填充

setw函数(全称set field width设置字段宽度)

cpp 复制代码
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	int a=12;
	cout<<setw(5)<<a<<endl;
    return 0;
}

可见是右对齐

cpp 复制代码
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	int a=12;
	cout<<a<<setw(5)<<"x"<<endl;
    return 0;
}

在12的右侧,将x右对齐5格

setfill函数(全称Set fill character设置填充字符)

cpp 复制代码
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	int a=12;
	cout << setw(10) << setfill('*') << a << endl;
    return 0;
}

setw(10)说明设置字段宽度为10,setfill('*')表明当不够时以*****填充剩余部分

2.控制数值格式

fixed:以固定小数点(即定点)表示浮点数,(不会以科学计数法展示了)

scientific:以科学计数法表示浮点数

setprecision:设置浮点数的精度(保留位数),以控制小数点后的数字位数,一般先固定小数点,再设置精度

cpp 复制代码
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	double pi=3.141592653589;
	cout << pi << endl;//原样打印 
	cout << fixed <<pi << endl;//固定点 
	cout << fixed << setprecision(3)<<pi<<endl;//先固定小数点+再设置精度(强制保留3位) 
	cout << scientific << pi << endl;
    return 0;
}

3.控制整数格式

dec:以十进制格式显示整数(默认)

"默认"的含义

设n为整型变量

cpp 复制代码
cout<<dec<<n<<endl;

等价为

cpp 复制代码
cout<<n<<endl;

hex:以十六进制格式显示整数

oct:以八进制格式显示整数

cpp 复制代码
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int n=100;
    cout<<dec<<n<<endl;
    cout<<hex<<n<<endl;
    cout<<oct<<n<<endl;
    return 0;
}

4.控制对齐方式

left:左对齐

right:右对齐(默认)

默认的含义:如果只写setw(),则默认右对齐

cpp 复制代码
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	int a=12;
	cout<<setw(5)<<right<<a<<endl;
	cout<<setw(5)<<left<<a<<'x'<<endl;
    return 0;
}
相关推荐
wjs20243 分钟前
jEasyUI 添加复选框指南
开发语言
迪霸LZTXDY5 分钟前
U-NET模型训练--图像标注脚本工具
开发语言·python
码界筑梦坊5 分钟前
119-基于Python的各类企业排行数据可视化分析系统
开发语言·python·信息可视化·数据分析·毕业设计·echarts·fastapi
习明然6 分钟前
记录下解决Python在windows 2008 Server 无法启动
开发语言·windows·python
凯瑟琳.奥古斯特8 分钟前
IP组播跨子网传输核心技术解析
java·开发语言·网络·网络协议·职场和发展
蜡笔小马9 分钟前
09.C++设计模式-外观模式
c++·设计模式·外观模式
xyq202413 分钟前
Razor VB 循环
开发语言
晚会者荣14 分钟前
C++11_3:包装器,智能指针
c++
古城小栈14 分钟前
Bun从Zig迁移至Rust:有何重大意义?
开发语言·后端·rust
handler0118 分钟前
TCP(传输控制协议)核心机制与底层原理
linux·网络·c++·笔记·网络协议·tcp/ip·操作系统