Convert int to a string in C++

In this post, we will discuss how to convert int to a string in C++.


 

1. Using std::to_string

The most common and efficient way is to use std::to_string method introduced with C++11 which returns a string representation of specified value. It is overloaded for all data types.

We can also use std::to_wstring which returns std::wstring.

 

Download   Run Code

Output:

10

 

2. Using string streams

Another good alternative is to use stringstream to convert between strings and other data types. The idea is to insert given integer into the stream and then write contents of its buffer to the std::string using its str() function. We need to include <sstream> header file for this.

 

Download   Run Code

Output:

10

 

3. Using Boost lexical_cast

We can also use boost lexical_cast library for converting an int to a string in C++. Please note that this solution is just a less-verbose alternative to previous approach as lexical_cast uses streams behind the scenes.

 

Download   Run Code

Output:

10

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Categories

Leave a Reply

Notify of
avatar
wpDiscuz