zoukankan      html  css  js  c++  java
  • c++格式化输入输出以及操纵器的使用

    C++格式化输入和输出

    1,ios类中定义的格式控制标志

    ios类中定义了一个数据成员:格式控制标志字,long x_flags

    x_flags每一位的状态值用枚举符号常量定义:如下列出常用几个

    enum{

    skipws  //跳过输入空格(skip whitespace)

    left   //输出左对齐调整

    right   //输出右对齐调整

    dec       //转化为十进制(in/out)(decimalism)

    oct        //转化为八进制(in/out)(octonary number system)

    hex       //转化为十六进制(in/out)(hexadecimal)

    showbase  //输出时显示所有数值的基数,八进制是前边加0,十六进制是前边加0x:例如: dec: 255 , cot:0377, hex:0xff

    showpoint  //输出时显示小数点和额外的零,即使不需要

    uppercase  //大写十六进制输出

    showpos  // 正整数显示前边加"+"(show positive sign)

    scientific  //用科学计数法显示浮点数

    fixed  //用正常的计数方法显示浮点数,与科学计数法相对应

    };

    2,操作符

    操作符:两类

    不带参数:定义在头文件 iostream.h

    带参数:定义在头文件iomanip.h

    (1)iostream.h 中的操作符(举例中num代表变量)

    oct  //cout<<oct<<num;八进制

        cin>>oct<<num;

    dec  //cout<<dec<<num;十进制

        cin>>dec>>num;

    hex  //cout<<hex<<num;十六进制

    ws  //cin>>ws;//跳过所有前导空白字符 (whitespace)

    endl  //cout<<endl  插入换行符并刷新流

    ends  //cout<<ends,输出空字符''

    flush  //cout<<flush 清空流

     (2)iomanip.h

    setprecision(int)  //设置数值精度(四舍五入)cout<<setprecision(5)<<num;

    setw(int)  //设置域宽度cout<<setw(4)<<num;

    setifosflags(long p)  //启用指定为p的标志 cout<<setifosflags(ios::left|ios::dec)//左对齐十进制输出

    resettifosflags(long p)  //取消指定为p的标志

    其他

    precision() 返回当前的浮点数精度值

    precision(val) 设置val为新的浮点数精度值, 并返回原值

    setf(flags) 添加格式标志flags, 返回所有标志的原本状态

    flags(long p) //启用指定为p 的标志

    示例:

    flags()

     

    int inum=255;
        cout<<"十进制方式"<<inum<<"	";
        cout.flags(ios::oct|ios::showbase);
        cout<<"八进制方式"<<inum<<"	";
        cout.flags(ios::hex|ios::showbase);
        cout<<"十六进制方式"<<inum<<endl;
    

     

      precison()

    void fn (float interest,float amount)
    {
        cout<<"RMB amount=";
        cout.precision(2);
        cout<<amount<<endl;
        cout<<"
    the interest=";
        cout.precision(4);
        cout<<interest<<endl;
    }
    
    int main ()
    {
        float f1=29.41560067;
        float f2=12.567188;
        fn(f1,f2);
        return 0;
    }
    

      

     

  • 相关阅读:
    【BZOJ 4151 The Cave】
    【POJ 3080 Blue Jeans】
    【ZBH选讲·树变环】
    【ZBH选讲·拍照】
    【ZBH选讲·模数和】
    【CF Edu 28 C. Four Segments】
    【CF Edu 28 A. Curriculum Vitae】
    【CF Edu 28 B. Math Show】
    【CF Round 439 E. The Untended Antiquity】
    【CF Round 439 C. The Intriguing Obsession】
  • 原文地址:https://www.cnblogs.com/zwx7616/p/11977407.html
Copyright © 2011-2022 走看看