c ++ cout output format (Encyclopedia)

1, alignment

//by 鸟哥 qq1833183060
#include <iomanip>
#include <iostream>

int main(void) {
    //1、方式1
    //左对齐
    std::cout <<std::left<< std::setw(20) << -123.456 << "|" << std::endl;
    //两端对齐
    std::cout <<std::internal<<std::setw(20) << -123.456 << "|" << std::endl;
    std::cout <<std::internal<<std::setw(20) << "hello world!" << "|" << std::endl;
    //右对齐
    std::cout <<std::right<< std::setw(20) << -123.456 << "|" << std::endl;

    //2、方式2
    //左对齐
    std::cout.flags(std::ios::left);
    std::cout <<std::setw(20) << -123.456 << "|" << std::endl;
    //两端对齐
    std::cout.flags(std::ios::internal);
    std::cout <<std::setw(20) << -123.456 << "|" << std::endl;
    std::cout <<std::setw(20) << "hello world!" << "|" << std::endl;
    //右对齐
    std::cout.flags(std::ios::right);
    std::cout <<std::right<< std::setw(20) << -123.456 << "|" << std::endl;
    return 0;
}

operation result: 

-123.456            |
-            123.456|
        hello world!|
            -123.456|
-123.456            |
-            123.456|
        hello world!|
            -123.456|

2, display an integer

//by 鸟哥 qq1833183060
#include <iomanip>
#include <iostream>
using namespace std;
int main(void) {
    cout<<showpos;//在十进制数字前显示+号
    cout<<uppercase;//将字母显示为大写
    cout << hex << setw(4) << 315 << setw(12) << -315 << endl;
    cout << dec << setw(4) << 315 << setw(12) << -315 << endl;
    cout << oct << setw(4) << 315 << setw(12) << -315 << endl;
    cout<<noshowpos;//取消showpos标记
    cout<<nouppercase;//取消uppercase标记
    cout << hex << setw(4) << 315 << setw(12) << -315 << endl;
    cout << dec << setw(4) << 315 << setw(12) << -315 << endl;
    cout << oct << setw(4) << 315 << setw(12) << -315 << endl;
    return 0;
}

operation result: 

 

 13B    FFFFFEC5
+315        -315
 473 37777777305
 13b    fffffec5
 315        -315
 473 37777777305

3, display binary prefixes

//by 鸟哥 qq1833183060
#include <iomanip>
#include <iostream>
using namespace std;
int main(void) {
    int n=66;
    int w=6;
    cout << showbase << setw(w) << hex << n<< setw(w) << oct << n << dec<<setw(w)<<n<<endl;
    cout << noshowbase << setw(w) << hex << n << setw(w) << oct << n << dec<<setw(w)<<n<< endl;
    return 0;
}

operation result:

 0x42  0102    66
    42   102    66

4, shown float

//by 鸟哥 qq1833183060
#include <iomanip>
#include <iostream>
using namespace std;

int main(void) {
    double f=31.415;
    
    for(int i=0;i<6;i++){  
        cout<<fixed;
        cout << setprecision(i) << f << endl;
        cout<<scientific;
        cout << setprecision(i) << f << endl;
    }
    
    return 0;
}

operation result:

31
3e +01
31.4
3.1e+01
31.41
3.14e + 01
31.415
3.141e+01
31.4150
3.1415e+01
31.41500
3.14150e+01

 

 

 

Published 14 original articles · won praise 3 · Views 1259

Guess you like

Origin blog.csdn.net/sinat_18811413/article/details/104109961