C++ 极简总结—— I/O 流类库(二)

C++ 格式化输入输出

c++的I/O流类库提供了两种控制格式输入输出的方法:

  1. 一种是使用ios类的成员函数。
  2. 另一种是使用控制符。
1、使用ios类的成员函数设置标志字。

(1) 、ios类中声明了一个数据成员用于记录当前流的格式化状态。这个数据成员就是标志字

  • 格式控制常量表
标志常量 Value 含义
ios::skipws 0x0001 跳过输入中的空白符
ios::left 0x0002 输出数据按输出域左对齐
ios::right 0x0004 输出数据按输出域右对齐
ios::internal 0x0008 数据的符号左对齐,数据本身右对齐,符号和数据之间为填充符
ios::dec 0x0010 十进制
ios::oct 0x0020 八进制
ios::hex 0x0040 十六进制
ios::showbase 0x0080 输出的数值数据前面带有基数符号(0或者0x)
ios::showpoint 0x0100 浮点数输出带有小数点
ios::uppercase 0x0200 用大写字母输出十六进制数
ios::showpos 0x0400 正数 ‘+’符号
ios::fixed 0x0800 使用定点数表示浮点数,没有指数部分
ios::scientific 0x1000 科学计数表示
ios::unitbuf 0x2000 完成输入操作后立即刷新流的缓冲区
ios::stdio 0x2000 完成输入操作后刷新系统的stdout、stderr
  • 操作标志字的公有函数

    • long flags() :返回标志字
    • long flags(long):更新标志字,返回更新前的标志字
    • long setf(long setbits,long field):将field 指定的标志位清零,将setbits所指的标志位置一
    • long setf(long):设置参数所指定的标志位
    • long unsetf(long):清除参数所指定的标志位

    例子:

#include 

using namespace std;

int main()
{
    double num = 12.34;
    cout<<"num = "<<num<<endl;
    cout.setf(ios::showpos);
    cout<<"num = "<<num<<endl;
    cout.setf(ios::scientific);
    
    cout<<"num = "<<num<<endl;
    return 0;
}

输出:

num = 12.34
num = +12.34
num = +1.234000e+001

或者:

#include 
using namespace std;
int main()
{
    double num = 12.34;
    cout<<"num = "<<num<<endl;
    cout.setf(ios::showpos|ios::scientific);
    cout<<"num = "<<num<<endl;
    return 0;
}

流格式标志字的每一位表示一种格式,格式位之间会有依赖关系。为了清除同类排斥位,ios类定义了几个公有静态符号常量:

static const long basefield;    //值为dec、oct、hex
static const long adjustfield;  //其值为 left、right、internal
static const long floatfield;   //scientific、fixed 

例子:

int num1 = 12;
cout.setf(ios::showbase);
cout.setf(ios::dec,ios::basefield);
cout<<"以十进制输出:"<<num1<<endl;

cout.setf(ios::oct,ios::basefield);
cout<<"以八进制输出:"<<num1<<endl;

cout.setf(ios::hex,ios::basefield);
cout<<"以十六进制输出:"<<num1<<endl;

结果:

以十进制输出:12
以八进制输出:014
以十六进制输出:0xc

(2)、使用ios类成员函数设置域宽,填充字符及输出精度
a.设置输出数据所占宽度的函数。

  • int width() 该函数用来返回当前的数据宽度
  • int width(int)设置数据输出宽度, 返回之前的数据宽度
    该函数设置的宽度仅对下一个流有效,下一个流输出之后,宽度又为0了。

b、填充当前宽度内的填充字符函数

  • char fill() 返回当前所使用的填充字符
  • char fill(char) 设置填充字符,返回之前用的字符

c、设置浮点数的输出精度

  • int percision() 返回当前浮点数的有效数字个数
  • int percision(int) 设置浮点数的有效数字个数,返回之前的值。

注意

  • 数据输出宽度在默认情况下为表示该数据所需要的最少字符数。
  • 默认情况下的填充字符为空格符
  • 如果设置的数据宽度小于所需的,则按默认宽度处理
  • 单精度7位,双精度15位,长双进度19位。

例子:

double values[] = {1.23,35.36,653.7,4358.24};
for(int i = 0;i < 4;i++)
{
    cout.setf(ios::left);
    cout.fill('*');
    cout.width(10);
    cout<<values[i]<<endl;
}

结果:

1.23******
35.36*****
653.7*****
4358.24***
2、使用控制符进行格式控制。

例子:

#include 
#include 
using namespace std;

int main()
{
    float num2 = 13.4;
    cout<<setiosflags(ios_base::left)<<setfill('*')<<setw(10)<<num2<<endl;
    return 0;
}

结果:

13.4******

你可能感兴趣的:(C/C++,c++)