[Pin to top] several methods for converting Integer type to string

Source: Internet
Author: User

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.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.