这里探讨C++如何将数据按指定的位数输出,如将所有打印在屏幕上的数据都按4位数输出,不够的前面补0。这里要用到C++的两个输出控制,setw(位数),和setfill(指定字符)。

不讲废话了,见下面代码:

    #include <iostream> 
    #include <iomanip>//一定要包含这个c++头文件,非常重要 

    using namespace std;  

    int main()  
    {  
        int test[4] = { 1, 12, 123, 1234 };  
        for (int i = 0; i < 4; ++i)  
        {  
            cout << setw(4) << setfill('0') << test[i] << " ";  
        }  
        cout << endl << endl;  
        return 0;  
    }  

这里需要注意加入

#include <iomanip>

头文件。

如果指定的是二进制数的指定位数,可以用bitset

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <cmath>
#include <set>
#include <queue>
#include <algorithm> 
#include <bitset>
#include <sstream> 
#include <iomanip>

using namespace std;


stringstream ss;




int main(){

    int a=1112333;
    string str="hello world";


    cout<<str<<endl;
    ss<<setw(20)<<setfill('#')<<std::hex<<a;

    ss>>str;

    cout<<str<<endl;

    return 0;
}






用bitset需要引入头文件:


#include <bitset>