std::string formatting like sprintf

前端 未结 30 2960
野趣味
野趣味 2020-11-22 04:42

I have to format std::string with sprintf and send it into file stream. How can I do this?

30条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 05:05

    C++20 std::format

    It has arrived! The feature is described at: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0645r9.html and uses a Python-like .format() syntax.

    I expect that the usage will be like:

    #include 
    #include 
    
    int main() {
        std::string message = std::format("The answer is {}.", 42);
    }
    

    I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a still doesn't support it.

    The API will add a new std::format header:

    The proposed formatting API is defined in the new header and should have no impact on existing code.

    The existing fmt library claims to implement it if you need the polyfill: https://github.com/fmtlib/fmt

    Implementation of C++20 std::format.

    and was previously mentioned at: std::string formatting like sprintf

    Hexadecimal format {:x}

    C++ cout hex values?

    Leading zeroes {:03}

    Print leading zeros with C++ output operator?

    Alignment left {:<}, right {:>}, center {:^}

    C++ alignment when printing cout <<

    Floating point precision {:.2}

    Set back default floating point print precision in C++

    Show sign on positive numbers {:+}

    How to print positive numbers with a prefix + in C++

    Show booleans as true and false: {:}

    Converting bool to text in C++

提交回复
热议问题