C++学习笔记(二)iomanip

     CONTENT :

  • setw(int)

  • setfill(char)

  • setiosflags

  • setbase(int)

  • setprecision(int)


 iomanip.h是I/O流控制头文件

1.setw(int n)

预设宽度
如, cout<<setw(5)<<996<<endl;
结果是:
空空996
 

2.setfill(char ch)

设置填充字符,常和setw一起使用

如,cout<<setfill('0')<<setw(5)<<996<<endl;

结果是:

00996

3.setiosflags

setiosflags(ios::fixed) 设置浮点数以固定的小数位数显示

setiosflags(ios::scientific) 设置浮点数以科学计数法表示

setiosflags(ios::left) 使左对齐

setiosflags(ios::right)使右对齐

setiosflags(ios::skipws) 忽略前导空格

setiosflags(ios::uppercase) 16进制数大写输出

setiosflags(ios::lowercase) 16进制小写输出

setiosflags(ios::showpoint) 强制显示小数点

setiosflags(ios::showpos) 强制显示符号(正数前加+)

setiosflags(ios::showbase)显示输出的进制

resetiosflags() 终止已经设置的输出格式状态,在括号中应指定内容

 

 

4.setbase(int n)

设置整数为n进制(n=8,10,16)

注:如果要2~36任意进制还是使用stdlib.h头文件中itoa函数  itoa():char *itoa( int value, char *string,int radix);

5.setprecision(int n)

C++中默认的输出数值有效位是6位

如果setprecision(n)与setiosflags(ios::fixed)合用,可以控制小数点右边的数字个数。setiosflags(ios::fixed)是用定点方式表示实数。
如、cout<<fixed<<setprecision(2)<<PI<<endl; 
结果是:
3.14
 
如果与setiosflags(ios::scientific)合用, 可以控制指数表示法的小数位数。setiosflags(ios::scientific)是用指数方式表示实数。
//代码1
#include<iostream> #include<iomanip> #define Pi 3.1415926 using namespace std; int main(){ cout<<showpos<<scientific<<setprecision(2)<<Pi<<endl; cout<<fixed<<setprecision(2)<<Pi<<endl; return 0; }

 

结果是:

 

 

也可以这么写:

//代码2
#include<iostream> #include<iomanip> #define Pi 3.1415926 using namespace std; int main(){ cout<<showpos<<setiosflags(ios::scientific)<<setprecision(2)<<Pi<<endl; cout<<setiosflags(ios::fixed)<<setprecision(2)<<Pi<<endl; return 0; }

 

 

还可以这么写:

//代码3
#include<iostream> #include<iomanip> #define Pi 3.1415926 using namespace std; int main(){ cout.flags(ios::scientific); cout<<setprecision(2)<<Pi<<endl; cout.flags(ios::fixed);
cout
<<setprecision(2)<<Pi<<endl; return 0; }

 

 

另外注意一下上面的代码1
用了showpos后面全有+号

但在第一句后面加一句 cout<<resetiosflags(ios::showpos);后面输出就不会有+;或中间单独对I/O流操作一下也可以消除+

 

 

 

 

 

 但这样又不行(cout.setf(ios::fixed);在这就没起作用?)

 

 

至于为什么。。。(小问号,你是否有很多朋友??????)我还没研究,下次有时间会专门再试

//涉足尚浅,如有不当,欢迎指出

posted @ 2020-03-14 20:38  //Mendax  阅读(378)  评论(0编辑  收藏  举报