Easiest way to convert int to string in C++

后端 未结 28 1756
甜味超标
甜味超标 2020-11-21 06:42

What is the easiest way to convert from int to equivalent string in C++. I am aware of two methods. Is there any easier way?

(1)



        
28条回答
  •  野的像风
    2020-11-21 07:23

    You can use std::to_string available in C++11 as suggested by Matthieu M.:

    std::to_string(42);
    

    Or, if performance is critical (for example, if you do lots of conversions), you can use fmt::format_int from the {fmt} library to convert an integer to std::string:

    fmt::format_int(42).str();
    

    Or a C string:

    fmt::format_int f(42);
    f.c_str();
    

    The latter doesn't do any dynamic memory allocations and is more than 10 times faster than std::to_string on Boost Karma benchmarks. See Fast integer to string conversion in C++ for more details.

    Note that both are thread-safe.

    Unlike std::to_string, fmt::format_int doesn't require C++11 and works with any C++ compiler.

    Disclaimer: I'm the author of the {fmt} library.

提交回复
热议问题