DNFM的博客

通过现象看本质!

[DNFM0047] C++ iostream 库的格式状态

每一个 iostream 库对象都维护一个格式状态(format state),它控制格式化操作的细节,比如整型值的进制数或浮点数值的精度。C++为程序员提供了一组预定义的操作符(manipulator),可用来修改对象的格式状态。操作符不会导致读写数据,只是改变流对象的内部状态。

1. boolalpha/noboolalpha操作符

    bool flag = true;
    cout << flag << endl;
    cout << boolalpha;
    cout << flag << endl;
    cout << noboolalpha;
    cout << flag << endl;

输出结果:


2. hex、oct、dec操作符

    int iVal = 0x11;
    cout << "Octal: " << oct << iVal << endl;
    cout << "Decimal: " << dec << iVal << endl;
    cout << "Hexadecimal: " << hex << iVal << endl;

输出结果:


3. showbase/noshowbase操作符

    int iVal = 0x11;
    cout << showbase;
    cout << "Octal: " << oct << iVal << endl;
    cout << "Decimal: " << dec << iVal << endl;
    cout << "Hexadecimal: " << hex << iVal << endl;
    cout << noshowbase;

输出结果:


4. uppercase/nouppercase
    int iVal = 0x11;
    cout << showbase << uppercase;
    cout << "Octal: " << oct << iVal << endl;
    cout << "Decimal: " << dec << iVal << endl;
    cout << "Hexadecimal: " << hex << iVal << endl;
    cout << noshowbase << nouppercase;

输出结果:


5. precision()/precision(n)成员函数

    double dVal = 3.1415926;
    int Accuracy = cout.precision();
    cout << Accuracy << endl;
    cout << dVal << endl;
    cout.precision(3);
    cout << dVal << endl;

输出结果:


6. setprecision(n)操作符(#include <iomanip>)

    double dVal = 3.1415926;
    cout << dVal << endl;
    cout << setprecision(3);
    cout << dVal << endl;

输出结果:


7. showpoint操作符

    cout << 10.00 << endl;
    cout << showpoint;
    cout << 10.00 << endl;

输出结果:


8. scientific/fixed操作符
    cout << scientific;
    cout << 10.0 << endl;
    cout << fixed;
    cout << 10.0 << endl;

输出结果:


如果希望把'e'输出为'E',则可以使用uppercase操作符,使用nouppercase操作符再次转换成小写。
9. noskipws/skipws
infile所关联的文本文件的内容为:
a b c
d

代码1:

    while (infile >> ch)
    {
        cout.put(ch);
    }

输出结果:


代码2:
    infile >> noskipws;
    while (infile >> ch)
    {
        cout.put(ch);
    }
    infile >> skipws;

输出结果:


10. setw()操作符

    int iVal = 16;
    double dVal = 3.14159;
    cout << setw(6) << iVal << endl;
    cout << setw(12) << dVal << endl;

输出结果:


11. setfill()操作符

    int iVal = 16;
    double dVal = 3.14159;
    cout << setw(10) << setfill('%');
    cout << iVal << endl;
    cout << setw(10) << setfill('%');
    cout << dVal << endl;

输出结果:


12. left/right操作符

代码1:

    int iVal = 16;
    double dVal = 3.14159;
    cout << left;
    cout << setw(10) << setfill('%');
    cout << iVal << endl;
    cout << setw(10) << setfill('%');
    cout << dVal << endl;
    cout << right;

输出结果:

代码2:

    int iVal = 16;
    double dVal = 3.14159;
    cout << right;
    cout << setw(10) << setfill('%');
    cout << iVal << endl;
    cout << setw(10) << setfill('%');
    cout << dVal << endl;
    cout << left;
输出结果:


DNFM0047(0)
阅读更多
上一篇[DNFM0048] C++ stringstream 类的用法
下一篇[DNFM0011] C++ iostream library overview
博主设置当前文章不允许评论。

C++ iostream

2011年04月21日 248KB 下载

没有更多推荐了,返回首页

关闭
关闭