欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > C6.【C++ Cont】cout的格式输出

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

2025/11/10 11:11:15 来源:https://blog.csdn.net/2401_85828611/article/details/143504050  浏览:    关键词:C6.【C++ Cont】cout的格式输出

目录

1.头文件

2.使用

1.控制宽度和填充

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

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

2.控制数值格式

3.控制整数格式

4.控制对齐方式


1.头文件

用cout进行格式化输出前,先引用头文件iomanip(全称input&output manipulators)

#include <iomanip>

2.使用

1.控制宽度和填充

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

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

可见是右对齐

#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设置填充字符)

#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:设置浮点数的精度(保留位数),以控制小数点后的数字位数,一般先固定小数点,再设置精度

#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为整型变量

cout<<dec<<n<<endl;

等价为

cout<<n<<endl;


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

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

#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(),则默认右对齐

#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;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词