Easiest way to convert int to string in C++

后端 未结 28 1793
甜味超标
甜味超标 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:21

    I usually use the following method:

    #include <sstream>
    
    template <typename T>
      std::string NumberToString ( T Number )
      {
         std::ostringstream ss;
         ss << Number;
         return ss.str();
      }
    

    It is described in details here.

    0 讨论(0)
  • 2020-11-21 07:21

    I use:

    int myint = 0;
    long double myLD = 0.0;
    
    string myint_str = static_cast<ostringstream*>(&(ostringstream() << myint))->str();
    string myLD_str = static_cast<ostringstream*>(&(ostringstream() << myLD))->str();
    

    It works on my Windows and Linux g++ compilers.

    0 讨论(0)
  • 2020-11-21 07:22

    C++17 provides std::to_chars as a higher-performance locale-independent alternative.

    0 讨论(0)
  • 2020-11-21 07:22

    Here's another easy way to do

    char str[100];
    sprintf(str, "%d", 101);
    string s = str;
    

    sprintf is a well-known one to insert any data into a string of the required format.

    You can convert a char * array to a string as shown in the third line.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-21 07:23

    First include:

    #include <string>
    #include <sstream>
    

    Second add the method:

    template <typename T>
    string NumberToString(T pNumber)
    {
     ostringstream oOStrStream;
     oOStrStream << pNumber;
     return oOStrStream.str();
    }
    

    Use the method like this:

    NumberToString(69);
    

    or

    int x = 69;
    string vStr = NumberToString(x) + " Hello word!."
    
    0 讨论(0)
提交回复
热议问题