输出格式控制setfill和setw使用



本文转自:http://blog.csdn.net/cjc211322/article/details/25463621

注意问题:

所使用的头文件为iomanip.h

例如:
cout<<'s'<<setw(8)<<'a'<<endl;
则在屏幕显示
s        a 
//s与a之间有7个空格,setw()只对其后面紧跟的输出产生作用,如上例中,表示'a'共占8个位置,不足的用空格填充。若输入的内容超过setw()设置的长度,则按实际长度输出。
setw()默认填充的内容为空格,可以setfill()配合使用设置其他字符填充。

cout<<setfill('*')<<setw(5)<<'a'<<endl;
则输出:
****a //4个*和字符a共占5个位置。


ep:

[cpp] view plain copy print ?
  1. <span style="font-size: 14px;">// test_max.cpp : 定义控制台应用程序的入口点。  
  2.   
  3. #include "stdafx.h"  
  4. #include <iostream>  
  5. #include <iomanip>                //setw(),setfill所在头文件     
  6. using namespace std;  
  7.   
  8. class NUM  
  9. {  
  10. public:  
  11.     NUM(int i):nm(i){}  
  12.     void incr() const  
  13.     {  
  14.         nm++;  
  15.     }  
  16.     void decr() const  
  17.     {  
  18.         nm--;  
  19.     }  
  20. public:  
  21.     mutable int nm;  
  22. };  
  23.   
  24. int main(void)  
  25. {  
  26.     NUM a(0);  
  27.   
  28.     string str="";  
  29.     for(int i=0;i<5;i++)  
  30.     {  
  31.         a.incr();  
  32.         cout<<setfill('*')<<setw(a.nm)<<str.c_str()<<endl;  
  33.     }  
  34.     for(int i=0;i<5;i++)  
  35.     {  
  36.         a.decr();  
  37.         cout<<setw(a.nm)<<str.c_str()<<setfill('*')<<endl;  
  38.     }  
  39.   
  40.     system("pause");  
  41.     return 0;  
  42. }</span>  
输出格式控制setfill和setw使用_第1张图片

你可能感兴趣的:(输出格式控制setfill和setw使用)