转自:http://blog.csdn.net/ididcan/article/details/4501529
如何设置cout的输出格式(转)
比如要设置输出的行宽,就有两种方法:
#include<iostram> #include<iomanip> using namepsace std; void main(){ // using str::width() cout.width(20); cout<<12<<endl; // using iomanip cout<<setw(20)<<12<<endl; }
两种方法是等价的,事实上setw(20)这个函数会返回一个manipulator对象,而cout所属的ostream类又重载了操作符< <,当它接收到一个manipulator对象时就会执行与该对象相应的操作。比如cout<<setw(20)所对应的处理代码大概 就会是这样的:
if(manipulatorIn.type==is_seting_width){ this->width( manipulator.width() ); }
因为第二种方法书写比较简单,所以这里只介绍第二种方法。
<iomanip>共有6个成员函数,分别如下:
resetiosflags // Clears the specified flags.
setbase // Set base for integers.
setfill // Sets the character that will be used to fill spaces in a right-justified display.
setiosflags // Sets the specified flags.
setprecision // Sets the precision for floating-point values.
setw // Specifies the width of the display field.
其中最常用的是setprecision,setw和setbase。
setprecision是设置输出的精度,即显示几位数字。它对后面的cout都有影响。
setw是设置输出的行宽,行宽如果小于precision的值,那么就按precision显示,行宽大于precision值就在数字前进行填充;setw()只对紧跟其后的数字有效。
setbase是设置输出数字的基数,如输出8进制数则用setbase(8);setbase后面的参数只能是8,10和16,其它参数无效。setbase对其后的cout都有影响。
setfill设置填充所用的字符。如果设定的行宽大于输出的精度,那么就会在数字前进行填充,而填充所用的字符则用setfill来设置。setfill对其后的cout都有影响。
setioflags与resetioflags是一对函数,它们用于改变一些flag值,这些flag值有:
所以事实上用这两个函数可以做很多事,只不过要记这些flag实在太麻烦了。
示例:
const double a=0.123456789; const int b=16; cout<< "a="<<a<<endl; cout<< "setprecision(5)"<<endl; cout<< setprecision(5)<<a<<endl; cout<< "setw(10)"<<endl; cout<< setw(10)<<a<<endl; cout << "setiosflags(ios_base::scientific)"<<endl; cout<< setiosflags(ios_base::scientific)<<a<<endl; cout<< "resetiosflags(ios_base::scientific)"<<endl; cout<< resetiosflags(ios_base::scientific)<<a<<endl; cout<< "b="<<b<<endl; cout<< "setbase(8)"<<endl; cout<<setbase(8)<<b<<endl;
结果如下:
a=0.123457 setprecision(5) 0.12346 setw(10) 0.12346 setiosflags(ios_base::scientific) 1.23457e-001 resetiosflags(ios_base::scientific) 0.12346 b=16 setbase(8) 20