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;
}
相关推荐
不想写代码的星星13 小时前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星6 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛7 天前
delete又未完全delete
c++
端平入洛8 天前
auto有时不auto
c++
郑州光合科技余经理9 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1239 天前
matlab画图工具
开发语言·matlab
dustcell.9 天前
haproxy七层代理
java·开发语言·前端