Several Methods to convert an integer to a string
Reprint please explain the source: http://blog.csdn.net/cywosp/article/details/8980633
Recently, I encountered the problem of converting the integer type into a string. I have collected some questions online and summarized several methods. As follows:
Method 1:
Template <typename T> static size_t convert (char Buf [], const T value) {static const char digits [] = "9876543210123456789"; static const char * zero = digits + 9; t I = value; char * P = Buf; do {int LSD = static_cast <int> (I % 10); I/= 10; * P ++ = zero [LSD];} while (I! = 0); If (value <0) {* P ++ = '-';} * P = '\ 0'; STD: reverse (BUF, P ); // # include <algorithm> return p-Buf;} static inline void inttostring (STD: string & out, const int value) {char Buf [32]; convert <int> (BUF, value); out. append (BUF );}
Method 2:
Static inline void inttostring (STD: string & out, const int value) {char Buf [32]; snprintf (BUF, sizeof (BUF), "% d", value ); // snprintf is thread safe # include <stdio. h> out. append (BUF );}
Method 3:
Static inline void inttostring (STD: string & out, const int value) {STD: strstream SS; // # include <strstream> SS <value; SS> out ;}
Method 4:
Static inline void inttostring (STD: string & out, const int value) {char Buf [32]; ITOA (value, Buf, 10); // # include <stdlib. h> out. append (BUF );}
In these methods, method 1 is fast.