您的位置:首页 > 编程语言 > C语言/C++

C++格式化输出

2014-05-13 15:38 330 查看
格式化输出主要包括控制状态标志、输出宽度、填充字符、输出精度等内容。其目的是实现特定的输出格式,实现方式有两种:使用状态标志和成员函数进行格式化输出和使用流操作符进行格式化输出。

1.使用状态标志和成员函数

输出标志由各种状态标志来确定,它们是定义在ios类中的枚举变量,引用时必须包含ios::前缀。常见的状态标志如下:



与此相关的主要是以下重要成员函数。

setf(long flags):设置状态标志

unsetf(long flags):清除状态标志

flaps()、flaps(long flags):获取状态标志

width()、width(int len):设置宽度函数

fill()、fill(char ch);设置填充字符

precision()、precision():设置输出精度函数

下面看下示例:

#include <iostream>
using namespace std;

int main()
{
cout<<"hello world";
cout.width(5);		//设置宽度为10;
cout.fill('*');		//宽度不满用*号填充;
cout<<78.5<<" ";
cout.setf(ios::scientific);	//使用科学计数法
cout.precision(3);	//精度为3
cout<<13.1124<<"  ";
cout.setf(ios::showpos|ios::left);//带正号,左对齐
cout<<1111<<endl;
return 0;
}

结果如下:



2.用流操作符进行格式输出

注意这里的头文件为iomanip.h



示例及结果如下

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
cout<<"hello world"<<setw(8)<<setfill('*')<<78.5<<scientific<<setprecision(3)<<213.3312<<" "<<showpos<<left<<1232<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: