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;
}
相关推荐
BadBadBad__AK43 分钟前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境13 小时前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境13 小时前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴1 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境3 天前
C++ 的Eigen 库全解析
c++
卷无止境4 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴4 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18005 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴6 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨6 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++