C++数字按指定的位数输出

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

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

    #include   
    #include //一定要包含这个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 

头文件。

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

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include  
#include 
#include  
#include 

using namespace std;


stringstream ss;




int main(){

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


    cout<20)<'#')<<std::hex<>str;

    cout<return 0;
}






用bitset需要引入头文件:


#include 

你可能感兴趣的:(模板)