c++输出格出 and 如何用cout实现各种输出

来源:互联网 发布:原油投资网络骗局 编辑:程序博客网 时间:2024/05/17 06:05

转载请注明出处http://blog.csdn.net/fanhansheng/article/details/52738259,谢谢。


选中行 ctrl +  shift + x 取消注释

选中行 ctrl +  shift +c  添加注释

shift + space  列出包含前缀名的所有名称

在网上找了一些关于cout的输出格式的资料, 做了一些整理。

dec, oct, hex, setbase, itoa

#include <iostream>
#include <cstdio>
#include <iomanip>
#include <cstdlib>

using namespace std;

int main()
{
    int number = 100;

    cout<<dec<<number<<endl;
    cout<<oct<<number<<endl;
    cout<<hex<<number<<endl;

    cout<<setbase(8)<<number<<endl;//setbase只允许8, 10, 16进制转化

    char str[25];
    itoa(number, str, 10); //按十进制转换   //itoa 头文件 #include <cstdlib>
    printf("integer = %d string = %s\n", number, str);
    itoa(number, str, 16); //按16进制转换   
    printf("integer = %d string = %s\n", number, str);

    return 0;
}

setw, setfill

#include <iostream>
#include <cstdio>
#include <iomanip>
#include <cstdlib>

using namespace std;

int main()
{
    int num = 2016;

    cout<<setw(5)<<setfill('^')<<num<<setw(10)<<setfill('_')<<num<<endl;

    return 0;
}

setorecision, setiosflags(ios::fixed), setiosflags(ios::scientific)

  1. #include <iostream.h>    
  2. #include <iomanip.h> //要用到格式控制符
  3. void main()   
  4. {  
  5.     double amount = 22.0/7;      
  6.     cout <<amount <<endl;      
  7.     cout <<setprecision(0) 
  8.     <<amount <<endl       
  9.     <<setprecision(1) <<amount <<endl       
  10.     <<setprecision(2) <<amount <<endl      
  11.     <<setprecision(3) <<amount <<endl       
  12.     <<setprecision(4) <<amount <<endl;
  13.   cout <<setiosflags(ios::fixed);      
  14.     cout <<setprecision(8) <<amount <<endl;
  15.   cout <<setiosflags(ios::scientific)
  16.     <<amount <<endl;
  17.      cout <<setprecision(6); //重新设置成原默认设置    
  18. }

运行结果为:
     3.14286
     3
     3
     3.1
     3.14
     3.143
     3.14285714
     3.14285714e+00

该程序在32位机器上运行通过。
  在用浮点表示的输出中,setprecision(n)表示有效位数。
  第1行输出数值之前没有设置有效位数,所以用流的有效位数默认设置值6:第2个输出设置了有效位数0,C++最小的有效位数为1,所以作为有效位数设置为1来看待:第3~6行输出按设置的有效位数输出。
  在用定点表示的输出中,setprecision(n)表示小数位数。
  第7行输出是与setiosflags(ios::fixed)合用。所以setprecision(8)设置的是小数点后面的位数,而非全部数字个数。
  在用指数形式输出时,setprecision(n)表示小数位数。
  第8行输出用setiosflags(ios::scientific)来表示指数表示的输出形式。其有效位数沿用上次的设置值8。
  小数位数截短显示时,进行4舍5入处理。

setiosflags(ios::showbase | ios::uppercase)


#include <iomanip>

using namespace std;

int main ()
{
    cout << hex;
    cout << oct;
    cout << setiosflags (ios::showbase | ios::uppercase);
    cout << 100 << endl;
    return 0;
}

#include <iostream>
#include <iomanip>
using namespace std;

int main ()
{
    cout.setf (ios::hex, ios::basefield);
    cout.setf (ios::showbase);
    cout<<100<<endl;
    cout.unsetf (ios::showbase);
    cout<<100<<endl;
    return 0;
}

0 0
原创粉丝点击