Convert a number to a string with specified length in C++

后端 未结 8 1355
情深已故
情深已故 2020-12-04 23:36

I have some numbers of different length (like 1, 999, 76492, so on) and I want to convert them all to strings with a common length (for example, if the length is 6, then tho

8条回答
  •  鱼传尺愫
    2020-12-05 00:07

    This is an old thread, but as fmt might make it into the standard, here is an additional solution:

    #include 
    
    int n = 999;
    
    const auto str = fmt::format("{:0>{}}", n, 6);
    

    Note that the fmt::format("{:0>6}", n) works equally well when the desired width is known at compile time. Another option is abseil:

    #include 
    
    int n = 999;
    
    const auto str = absl::StrFormat("%0*d", 6, n);
    

    Again, abs::StrFormat("%06d", n) is possible. boost format is another tool for this problem:

    #include 
    
    int n = 999;
    
    const auto str = boost::str(boost::format("%06d") % n);
    

    Unfortunately, variable width specifier as arguments chained with the % operator are unsupported, this requires a format string setup (e.g. const std::string fmt = "%0" + std::to_string(6) + "d";).

    In terms of performance, abseil and fmt claim to be very attractive and faster than boost. In any case, all three solutions should be more efficient than std::stringstream approaches, and other than the std::*printf family, they do not sacrifice type safety.

提交回复
热议问题