[c++ primer plus]使用cout格式化輸出

1.進制

    cout << _T(" 17.3 修改顯示時使用的計數系統"<< endl;
    
int n;
    n 
= 255;
    dec(cout);              
// cout << dec;
    cout << "dec : " << n << endl;
    oct(cout);              
// cout << oct;
    cout << "oct : " << n << endl;
    hex(cout);              
// cout << hex ;
    cout << "hex : " << n << endl;
    dec(cout);              
// 不要影響其它人

 
2. 輸出寬度
 
    cout << _T(" 17.4 調整字段寬度"<< endl;
    
int w = cout.width(30);
    cout 
<< "default field width = " << w << ":" << endl;
    cout.width(
5);
    cout 
<< "N" << "";
    cout.width(
8);
    cout 
<< "N * N" << ":" << endl;
    
for(long i=1; i<=100; i*=10)
{
        cout.width(
5);
        cout 
<< i << "";
        cout.width(
8);
        cout 
<< i * i << ":" << endl;
    }

    cout.width();

3. 填充字符

    cout << _T(" 17.5 填充字符"<< endl;
    cout.fill(
'*');
    
int w = cout.width(30);
    cout.width(
5);
    cout 
<< "N" << "";
    cout.width(
8);
    cout 
<< "N * N" << ":" << endl;
    
for(long i=1; i<=100; i*=10)
    
{
        cout.width(
5);
        cout 
<< i << "";
        cout.width(
8);
        cout 
<< i * i << ":" << endl;
    }

    cout.width();
    cout 
<< endl << endl;

4. 浮點數顯示精度

    cout << _T(" 17.6 設置浮點數的顯示精度"<< endl;
    
float f1 = 23.3232;
    
float f2 = 1.9 + 8.0 / 9.0;
    cout 
<< "f1 = " << f1 << endl;
    cout 
<< "f2 = " << f2 << endl;
    
// 設置精度爲2
    cout.precision(2);
    cout 
<< "f1 = " << f1 << endl;
    cout 
<< "f2 = " << f2 << endl;
    
// 解除設定
    cout.precision();

5. setf用法

    cout << _T(" 17.7 設置精度爲2打印末位的0和小數點"<< endl;
    
float f1 = 23.3232;
    
float f2 = 1.9 + 8.0 / 9.0;
    cout 
<< "f1 = " << f1 << endl;
    cout 
<< "f2 = " << f2 << endl;
    
// 設置精度爲2打印末位的0和小數點
    cout.setf(ios_base::showpoint);
    cout 
<< "f1 = " << f1 << endl;
    cout 
<< "f2 = " << f2 << endl;
    
// 解除設定
    cout.setf(ios_base::unitbuf);

6. setf高級用法

    cout << _T(" 17.7 setf 高級用法"<< endl;
    cout.setf(ios_base::showpos);
    cout 
<< 63 << endl;
    cout.setf(ios_base::uppercase);
    cout 
<< "A string" << endl;
    cout.setf(ios_base::showbase);
    cout 
<< 437 << endl;
    cout.setf(ios_base::boolalpha);
    cout 
<< true << endl;
    cout 
<< false << endl;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章