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;
}
相关推荐
hqxstudying1 小时前
Java异常处理
java·开发语言·安全·异常
小坏坏的大世界3 小时前
C++ STL常用容器总结(vector, deque, list, map, set)
c++·算法
wjs20244 小时前
状态模式(State Pattern)
开发语言
我命由我123454 小时前
Kotlin 数据容器 - List(List 概述、创建 List、List 核心特性、List 元素访问、List 遍历)
java·开发语言·jvm·windows·java-ee·kotlin·list
liulilittle4 小时前
C++ TAP(基于任务的异步编程模式)
服务器·开发语言·网络·c++·分布式·任务·tap
励志要当大牛的小白菜5 小时前
ART配对软件使用
开发语言·c++·qt·算法
PAK向日葵6 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
爱装代码的小瓶子7 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
Maybe_ch9 小时前
.NET-键控服务依赖注入
开发语言·c#·.net
超浪的晨9 小时前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发