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

这里探讨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>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值