码迷,mamicode.com
首页 > 编程语言 > 详细

C++流操作算子

时间:2016-04-22 19:52:33      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

用过c语言的都知道c语言的精度格式控制非常简单容易,刚学C++也许还不懂怎么在C++中使用这些功能.这里有两个方法来使用这些功能.

变量使用:

    int n = 64;
    double d = 123.45;
    double d2 = 0.0183;

一.使用流操纵算子
首先得包含头文件
1.宽度控制

    cout << n << ‘#‘ << endl;
    //宽度控制不会影响下一个变量
    cout << setw(10) << n << ‘#‘ << endl;//默认右对齐
    cout << n << ‘#‘ << endl;

技术分享

2.对齐控制

    //对齐控制会影响下面的变量对其方式
    cout << setw(10) << setiosflags(ios::left) << n << ‘#‘ << endl;//左对齐
    cout << setw(10) << n << ‘#‘ << endl;
    cout << setw(10) << setiosflags(ios::right) << n << ‘#‘ << endl;//还原成右对齐
    //cout << setw(10) << resetiosflags(ios::left) << n << ‘#‘ << endl << endl;//还原成右对齐

技术分享

3.填充控制

    //填充控制会影响下面的输出
    cout << setw(10) << setfill(‘@‘) << n << ‘#‘ << endl;
    cout << setw(10) << n << ‘#‘ << endl;
    cout << setw(10) << setfill(‘ ‘) << n << ‘#‘ << endl; //还原成空格填充

技术分享

4.精度控制

    //精度控制会影响下面的输出
    cout << setprecision(4) << d << endl; //控制有效数字的位数
    cout << setprecision(2) << d2 << endl;//四舍五入,而不是简单的截断
    cout << d << endl;
    cout << setiosflags(ios::fixed);      //控制小数点后面的位数
    cout << setprecision(4) << d << endl; //同样是四舍五入
    cout << setprecision(2) << d2 << endl;

技术分享

5.进制控制

    cout << "dec: " << n << endl;
    cout <<"oct: "<<oct << n << endl;
    cout << "hex: " << hex << n << endl;   
    cout << n << endl;
    cout << setiosflags(ios::showbase);//显示对应进制前面的符号
    cout << "dec: " << dec <<n << endl;
    cout << "oct: " << oct << n << endl;
    cout << "hex: " << hex << n << endl;
    cout << setbase(8) << n << endl;   //进制输出
    cout << setbase(10) << n << endl;
    cout << setbase(16) << n << endl;

技术分享

二.以流成员函数的方式(不用包含iomanip头文件)
1.宽度控制

    cout << n << endl;
    cout.width(10);
    cout << n << ‘#‘ << endl;

技术分享

2.对齐控制

    cout << n << endl;
    cout.width(10);
    cout.setf(ios::left);
    cout << n << ‘#‘ << endl;
//  cout.width(10);
//  cout.setf(ios::right);
//  cout << n << ‘#‘ << endl;
    cout.width(10);
    cout.unsetf(ios::left);
    cout << n << ‘#‘ << endl;

技术分享

3.填充控制

    cout << n <<‘#‘<< endl;
    cout.width(10);
    cout.fill(‘@‘);
    cout << n << ‘#‘ << endl;
    cout.width(10);
    cout << n << ‘#‘ << endl;
    cout.width(10);
    cout.fill(‘ ‘);
    cout << n << ‘#‘ << endl;

技术分享

4.精度控制

    cout.precision(2);   //这个会影响下面的输出
    cout << d << endl;
    cout << d2 << endl;
    cout.setf(ios::fixed);  //控制小数点位数
    cout << d << endl;
    cout << d2 << endl;

技术分享

5.进制控制

    cout.unsetf(ios::dec); //要切换进制的时候需要先去掉原先的进制
    cout.setf(ios::oct);
    cout << n << endl;

输出为100.

C++流操作算子

标签:

原文地址:http://blog.csdn.net/qq_18297675/article/details/51213266

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!